Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript, parseInt behavior when passing in a float number

I have the following two parseInt() and I am not quite sure why they gave me different results:

alert(parseInt(0.00001)) shows 0;

alert(parseInt(0.00000001)) shows 1

My guess is that since parseInt needs string parameter, it treats 0.00001 as ""+0.00001 which is "0.00001", therefore, the first alert will show 0 after parseInt. For the second statement, ""+0.00000001 will be "1e-8", whose parseInt will be 1. Am I correct?

Thanks

like image 458
AlliceSmash Avatar asked Apr 19 '14 20:04

AlliceSmash


People also ask

How do you parse a float?

The parseFloat() function is used to accept the string and convert it into a floating-point number. If the string does not contain a numeral value or If the first character of the string is not a Number then it returns NaN i.e, not a number.

How do you check if a number is a float JavaScript?

Check if the value has a type of number and is not an integer. Check if the value is not NaN . If a value is a number, is not NaN and is not an integer, then it's a float.

What happens if you parseInt a number?

The parseInt function converts its first argument to a string, parses that string, then returns an integer or NaN . If not NaN , the return value will be the integer that is the first argument taken as a number in the specified radix .

Does parseInt round down?

parseInt() is an easy way to parse a string value and return a rounded integer. If you're working with a special use-case and require a different numerical base, modify the radix to your choosing.


1 Answers

I believe you are correct.

parseInt(0.00001) == parseInt(String(0.00001)) == parseInt('0.00001') ==> 0

parseInt(0.00000001) == parseInt(String(0.00000001)) == parseInt('1e-8') ==> 1
like image 78
Barmar Avatar answered Sep 19 '22 02:09

Barmar