Behavior difference between parseInt() and parseFloat() [duplicate]

Why is this behavior difference between parseInt() and parseFloat()?

I have a string that contains 08 in it.

When I write this code:


The following output is generated:


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


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.