Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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?

like image 243
Naveed Butt Avatar asked Mar 02 '12 05:03

Naveed Butt


2 Answers

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).

like image 61
Paul Avatar answered Oct 13 '22 21:10

Paul


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
like image 36
Charlie Pops Avatar answered Oct 13 '22 21:10

Charlie Pops