← coderrocketfuel.com

How to Round a Number to Decimal Points in Node.js

How do you round a number to a specific decimal point using Node.js?

Node.js has a built-in method called toFixed() that formats a number using fixed-point notation. The toFixed() method takes one number parameter that tells it how many digits to appear after the decimal point. This number can be a value between 0 and 20.

And the method will return a string value representing the new number generated using fixed-point notation.

Here's an example:

const number = 42.235888

const newNumber = number.toFixed(2)
// newNumber = 42.24

Notice that the .toFixed(2) method transforms the 42.235888 number to a new version with only 2 decimal points.

What happens if you applied the decimal point to a whole number?

Here's a code example for that:

const number = 42

const newNumber = number.toFixed(3)
// newNumber = 42.000

Notice how the new number created by the .toFixed(3) method has 3 digits behind the decimal point even though they're zero.

Pretty cool, right?

Let's go over one more example where we want to transform a number with decimal points to a rounded whole number.

Here's the code:

const number = 42.68231

const newNumber = number.toFixed(0)
// newNumber = 43

If you give a value of 0 to the .toFixed() method, it will round the new number to a whole number.