How to Round to a Certain Number of Decimal Places in JavaScript

The built-in Math.round() function doesn’t let you specify a precision for rounding decimal numbers. Here’s how to write a round function to round to a certain number of decimal places.

Dr. Derek Austin 🥳
The Startup
Published in
6 min readJun 10, 2020

--

Photo by Tyler Easton on Unsplash

There is no built-in method to round to a certain number of digits in JavaScript. You might think the Math.round() function would take an argument specifying a desired precision, but it doesn’t.

“The Math.round() function returns the value of a number rounded to the nearest integer.” — MDN Docs

You might be tempted to reach for an external library like math.js, whose math.round function takes the number of decimals as an argument, but it’s easy to accomplish this task just using vanilla JavaScript.

In this article, you will learn how to use Math.round() to round a JavaScript number to a certain number of decimal places with a little arithmetic.

Using Math.round() to round decimal values

Since Math.round() will only round a floating point value to the nearest integer value, we can use that to our advantage to…

--

--

Dr. Derek Austin 🥳
The Startup

I write about real-world programming career advice, MongoDB vs. PostgreSQL, Git, React, JavaScript, VS Code, TypeScript, and Next.js. Doctor of Physical Therapy