Puzzle time: Yes, this is not good code, but do you know why this quirk occurs? Answer will be posted (or retweeted) later :-) Clue: An intermediate step occurs in the transformation of the supplied number.
String(0.000001) = "0.000001" => parseInt: 0 String(0.0000001) = "1e-7" => parseInt: 1
Had you used #TypeScript, it wouldn't have even compiled. parseInt isn't quirky. Implicit coercion is. parseInt doesn't even take number as the argument! It takes string!
parseInt(val) 1. Converts val to string. Numbers get converted to exponential notation if they have too many digits (like 0.0000001 has). 2. Strips anything after, and including, the first non-digit 3. Converts to integer 0.000001→"0.000001"→"0"→0 0.0000001→"1e-7"→"1"→1
"parseInt" function convert value to the string. So String(0.0000001) will return 1e-7, and parseInt('1e-7') will return 1.
parseInt(String(0.0000001))==parseInt(0.0000001) String(0.0000001)=>"1e-7" so parseInt(0.0000001) == 1 but parseInt(String(0.000001))==parseInt(0.000001) String(0.000001)=>"0.000001" so parseInt(0.000001) == 0 if we use parseInt(Num(0.0000001)) == 0
Because it first use toString method. And it can’t parse numbers less than 1e-6 and bigger than 1e21.
The number is first converted to a string — and unfortunately 0.000001 is converted to exponent format (1e-7) which parseInt will read and take the ‘1’.
Interesting! Just sent in a pull request with this quirk to #wtfjs github.com/denysdovhan/wt… Thanks @JavaScriptDaily
the second number will be converted to the exponential notation. parseInt takes a string as an arg so it is basically parseInt(‚1e-1000‘) or something like that. Everything after the e will be cut off.
not that it makes a difference in this case, but you should always practice safe `parseInt` by using a radix...
parseInt takes a string as first parameter. 0.0000001 is transformed to 1e-7... so parseInt("1e-7") and that's why the result is 1
United States الاتجاهات
- 1. StandX 4,892 posts
- 2. #NationalCatDay 1,725 posts
- 3. Huda 19.5K posts
- 4. South Korea 136K posts
- 5. FOMC 34.1K posts
- 6. #SpaceMarine2 N/A
- 7. Good Wednesday 32.2K posts
- 8. #wednesdaymotivation 4,226 posts
- 9. Hump Day 18.2K posts
- 10. $XHLD $0.27 N/A
- 11. Jay Z 8,287 posts
- 12. Happy Hump 11.2K posts
- 13. #MAYATVAWARDS2025 1.67M posts
- 14. #Wednesdayvibe 2,222 posts
- 15. Marcedes Lewis N/A
- 16. $NVDA 104K posts
- 17. Mandy 15.5K posts
- 18. Nvidia 85.6K posts
- 19. Xabi 21.8K posts
- 20. ZNN AT MAYA25 817K posts
Something went wrong.
Something went wrong.