TIL more scary floats in Javascript
POSTED ON:
TAGS: integer javascript advanced-js
This is another wonkiness of Javascript, and why you should avoid using Floats.
Why?
String(0.5); // => '0.5'
String(0.05); // => '0.05'
String(0.005); // => '0.005'
String(0.0005); // => '0.0005'
String(0.00005); // => '0.00005'
String(0.000005); // => '0.000005'
String(0.0000005); // => '5e-7'
Care must be taken when trying to extract the integer part of floats using parseInt().
Floats smaller than 10-6 (e.g. 0.0000005 which is same as 5*10-7) conversed to a string are written in the exponential notation (e.g. 5e-7 is the exponential notation of 0.0000005). That's why using such small floats with parseInt() leads to unexpected results: only the significat part (e.g. 5 of 5e-7) of the exponential notiation is parsed.
REFERENCE:
https://www.reddit.com/r/ProgrammerHumor/comments/shmec9/we_all_love_javascript/
https://dmitripavlutin.com/parseint-mystery-javascript/
Related TILs
Tagged: integer