And How to Remove the trailing Zeros on a Floating Point Number
3 min read
It's also super useful when coding applications too. The classic example is the calculator app, where you're taking in input values from the users as strings, and you need to verify that these values are valid numbers (or operators).
How do you check if a String is a Number?
isNaN(str). Which translates to "is Not a Number". It returns true if
str is not a number, and false if it IS a number.
If we use
!isNaN(str) we get true if
str is a number....
!isNaN('👾123') // => false !isNaN('😺') // => false !isNaN('456') // => true // works for floats too !isNaN('-2.5') // => true
Great, now how do I Convert the String to a Number?
There are 4 ways to type convert a string to a number (if it is a number).
WARNING: If the string is NOT a number, do NOT attempt to convert it to a number, because you'll either get
NaN back or sometimes
0 if you convert an empty string or space to a number. Good luck finding that bug in your code!** 🤬
So ALWAYS check if it's a number using
Got it? Cool! Let's type convert:
// for integers +'456' // => 456 parseInt('456') // => 456 Number('456') // => 456 // for floating point numbers +'-2.600' // => -2.6 parseFloat('-2.600') // => -2.6 Number('-2.600') // => -2.6
parseInt(...) ONLY works for integers, if you give it a float it will cut off everything after the
How to Remove Trailing (and Leading) Zeros from a Floating Point Number
Notice I added some zeros at the end of
-2.6 I did that to illustrate something cool: by type converting a string to a float, all unnecessary floating point zeros that come after AND before will be removed.
This really comes in handy.
+'-000002.600' // => -2.6
Related trick: if you have a float with a lot of trailing zeros you want to get rid of, just convert it to a string THEN back to a number with
const annoyingNumber = 1.230000000000; const cleanNumber = +annoyingNumber.toString(); console.log(cleanNumber); // => 1.23
Hands down, my favorite is the
+ operator. It's just one character long, gotta love it! 😻
What's your favorite?
Did you find this article valuable?
Support Amit Mehta by becoming a sponsor. Any amount is appreciated!