Why is this behavior difference between
I have a string that contains
08 in it.
When I write this code:
alert(hfrom); alert(parseInt(hfrom)); alert(parseFloat(hfrom));
The following output is generated:
08 0 8
parseFloat return two different results in this case?
parseInt() assumes the base of your number according to the first characters in the string. If it begins with
0x it assumes base 16 (hexadecimal). Otherwise, if it begins with
0 it assumes base 8 (octal). Otherwise it assumes base 10.
You can specify the base as a second argument:
alert(parseInt(hfrom, 10)); // 8
From MDN (linked above):
If the input string begins with "0x" or "0X", radix is 16 (hexadecimal). If the input string begins with "0", radix is eight (octal). This feature is non-standard, and some implementations deliberately do not support it (instead using the radix 10). For this reason always specify a radix when using parseInt. If the input string begins with any other value, the radix is 10 (decimal).
you should always include the radix param with
parseInt('013', 10) otherwise it can convert it to a different numeric base:
parseInt('013') === 11 parseInt('013', 10) === 13 parseInt('0x13') === 19
©2020 All rights reserved.