Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange and inconsistent behaviour of parseInt on decimal fractions [duplicate]

Tags:

javascript

v8

console.log(parseInt(0.0000008))
// > 8

console.log(parseInt(0.000008))
// > 0

console.log(parseInt(0.0000008, 10))
// > 8

console.log(parseInt(0.000008, 10))
// > 0

The above code was run in Google Chrome Version 62.0.3202.94 (Official Build) (64-bit) on macOS Sierra Version 10.12.6.

As you can see, the behaviour does not depend on whether or not you specify the radix.

Note: I usually use ~~ instead of using parseInt, it looks safer.

Why am I getting these results?

like image 665
lnshi Avatar asked Nov 22 '17 05:11

lnshi


1 Answers

parseInt stringifies its first argument if the argument isn't already a string. 0.000008 stringifies to '0.000008', but 0.0000008 stringifies to '8e-7'.

If parseInt finds an invalid character in the input, it ignores that character and everything after it. . and e are invalid for base 10 (and . would be invalid for any base), so parseInt sees '0.000008' as '0' and '8e-7' as '8'.

I don't know what you were trying to do here, but parseInt is not the tool to do it.

like image 92
user2357112 supports Monica Avatar answered Oct 31 '22 07:10

user2357112 supports Monica