JavaScript article thumbnail image.

How do you round a number to a specific decimal point using JavaScript?

JavaScript 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 three 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.

Hopefully, this article was helpful in your coding endeavors.

Thanks for reading and happy coding.

About the author

Hi, I'm Nick Major. I'm a software developer from Wisconsin, United States.

I create free and premium courses, have published hundreds of informational coding articles, and am currently a Frontend Software Engineer at RoundingWell.

You can read more about me here.

Picture of Nick Major.