5 Essential JS Number Methods to Learn

Justin Lee
CodeX
Published in
3 min readNov 2, 2022
Image by Prawny from Pixabay

In Javascript, commonly used objects such as arrays, numbers, and dates have powerful built-in methods. Due to this fact, in most cases, we do not need to reinvent the wheel. A number is usually the first object every programmer is exposed to (e.g. 1, 2, 3.3, 4, -1). Here are commonly used methods for the Number object.

Number Methods

1. toString()

Converts a number to a string. For integers larger than 21 digits, it is represented with scientific notation (e.g. 1e+22).

2. toFixed(digits)

Fixes the number of digits that appear after the decimal and converts this to a string. If the digits parameter is not specified, the default will be set to 0.

3. toPrecision(precision)

Fixes the number of digits that appear in total and converts this to a string (excluding the actual decimal).

If the precision parameter is not specified, the default output will be the same as toString().

4. parseInt(string)

Converts a string to an integer. Space before the number string is ignored. The function converts the first integer that is detected and ignores all characters that come after a non-integer character (e.g. space, decimal, comma, etc).

Unlike other methods, to use this method, we use Number followed by .. Also, there is an optional parameter named radix, but let us ignore it for now.

5. parseFloat()

Converts a string to a floating number that includes decimals. Space before the number is ignored. Like parseInt(), only the first floating point string is converted.

Code

Conclusion

Feel free to copy and paste the code below and play around with the inputs and outputs. For example, like toString() the example above, some numbers are simply too large to be represented by the number object (e.g. 9007199254740993). In this case, use BigInt. Make sure to master the ins and outs of these Number methods when you get the chance!

--

--

Justin Lee
CodeX
Writer for

The path towards the full stack. Previously 5+ years as a senior data scientist @ e-commerce, consulting, and investment banking.