The mysteries and potentials of Javascript will always be numerous and expanding, but learning the fundamentals and core of options of the language will always remain invaluable tools. In this blog we will explore some of Javascript Number Methods and what they do. We will also describe how to use them by giving some code examples.
Ol’ Reliable: parseInt([string]) and parseInt([string]) and [num].toString( )
Ever receive a string that is actually a number and you need to use it as a number but the code keeps breaking because it’s the wrong value type? I know I have, and I sometimes I need a string instead of an number, which is these methods will always be in my back pocket.
let x = '20.20'; // string of 20.20
parseInt(x); // returns the number 2020
parseFloat(x); // returns the float 20.20
let z = 42; // number 42
z.toString(); // returns the string '42'
toExponential and toFixed and toPrecision
These three methods are very similar with some minor, but very important, nuances. To exponential doesn’t actually size up or down a number, but rather it returns the same number in the form of an exponential with the desired number of characters
let x = 8.565;
x.toExponential(2); // returns 8.57e+0
x.toExponential(3); // returns 8.565e+0
x.toExponential(4); // returns 8.5650e+0
let y = 5268.2;
y.toExponential(2); // returns 5.27e+3
y.toExponential(3); // returns 5.268e+3
y.toExponential(4); // returns 5.2682e+3
y.toExponential(5); // returns 5.26820e+3
toFixed( ) also takes in a number and it also returns a value that is determined by the desired number of decimal places, but it won’t be in an exponential form and it will be a STRING. Make sure to remember that last part.
let x = 6.26185;
x.toFixed(0); // returns '6'
x.toFixed(1); // returns '6.3'
x.toFixed(2); // returns '6.26'
x.toFixed(4); // returns '6.2619'
toPrecision( ) is very similar to toFixed( ), except that this method does return a number, not a string.
let x = 7.91538;
x.toPrecision(0); // returns 8
x.toPrecision(1); // returns 7.9
x.toPrecision(2); // returns 7.92
x.toPrecision(4); // returns 7.9154
Finally, something simpler: Number( )
Maybe you don’t need to do anything to your numbers and strings except convert some variables to numbers, determine if the variable is even a number, or just a simple ‘yes/no’ response in the form of a 1 or a 0.
Number(true); // 1
Number(false); // 0
Number("33"); // 33
Number(33); // 33
Number("33,33"); // NaN
Conclusion
Javascript is a powerful language that has been used for many years and in many frameworks to create amazing applications, but all of this came from its foundations and it’s important to look it up and play with it for a bit to gain a solid and clear understanding. Even if it as simple as turning a ‘1’ to a 1.