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. Louisville 73.5K posts
- 2. Jets 133K posts
- 3. Virginia 230K posts
- 4. MD-11 16.6K posts
- 5. Honolulu 7,511 posts
- 6. #OlandriaxGlamourWOTY 2,055 posts
- 7. Azzi 6,813 posts
- 8. Jared Isaacman 6,549 posts
- 9. #AreYouSure2 40.3K posts
- 10. Madrid 434K posts
- 11. UPS Flight 2976 13.8K posts
- 12. Colts 64.6K posts
- 13. Jay Jones 27K posts
- 14. Courtois 69.5K posts
- 15. Cheney 287K posts
- 16. Sarah Strong 1,416 posts
- 17. #いい推しの日 828K posts
- 18. UConn 5,526 posts
- 19. Miyares 14.6K posts
- 20. #JiminxJungKook 38.8K posts
Something went wrong.
Something went wrong.