12

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?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
lnshi
  • 2,310
  • 3
  • 19
  • 42
  • what you are doing here with parseInt with such arguments. – manikant gautam Nov 22 '17 at 05:33
  • 2
    The only strange thing is that you are calling `parseInt` on a number while it clearly expects a string. Did you mean to use `Math.floor`? – Bergi Nov 22 '17 at 07:46
  • @guys, see the comment I put at the below already accepted answer, pls don't keep asking me the use case and why I invoke the function like that – lnshi Nov 22 '17 at 08:17
  • use `~~` or `Math.floor`, not `parseInt`. It's simply not the right tool for the job (converting number to int) – edc65 Nov 22 '17 at 09:03

1 Answers1

21

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • 1
    Ah, I see, it is `toString`'s behaviour (http://www.ecma-international.org/ecma-262/6.0/#sec-tostring). Thank you very much, i wasn't trying to do anything, just casually observed this behaviour. – lnshi Nov 22 '17 at 05:15