Why is this behavior difference between parseInt()
and parseFloat()
?
I have a string that contains 08
in it.
When I write this code:
alert(hfrom[0]);
alert(parseInt(hfrom[0]));
alert(parseFloat(hfrom[0]));
The following output is generated:
08
0
8
Why does parseInt
and 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[0], 10)); // 8
From MDN (linked above):
If radix is undefined or 0, JavaScript assumes the following:
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()
ex parseInt('013', 10)
otherwise it can convert it to a different numeric base:
parseInt('013') === 11
parseInt('013', 10) === 13
parseInt('0x13') === 19
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With