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 Trends
- 1. Good Monday 30.1K posts
- 2. #RomanEmpireByBangChan 18.2K posts
- 3. #MondayMotivation 27.5K posts
- 4. ROMAN EMPIRE OUT NOW 15.3K posts
- 5. Jayden Daniels 26.4K posts
- 6. Talus 23.2K posts
- 7. $KITE 4,603 posts
- 8. jungkook 584K posts
- 9. 60 Minutes 84.3K posts
- 10. #STARDOM 5,664 posts
- 11. Dan Quinn 7,285 posts
- 12. Victory Monday 1,054 posts
- 13. Perle Labs 5,243 posts
- 14. #River 7,425 posts
- 15. Seahawks 39.4K posts
- 16. Godzilla 48.7K posts
- 17. Sam Darnold 15.5K posts
- 18. Commanders 51.2K posts
- 19. Snopes 3,553 posts
- 20. #RaiseHail 8,951 posts
Something went wrong.
Something went wrong.