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

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.

Image for postPhoto 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 accomplish the task of rounding to a certain number of decimal places.

You simply need to take the number of decimal places you want, multiply the floating point value by 10 raised to the power of that number, and then round. That moves the decimal place, allowing you to round, and then you just divide by the factor of 10 that you had multiplied by.

For example, if you want to round 0.507 to 1 decimal place, you multiply by 10 to get 5.07, round to get 5, then divide by 10 to get 0.5.

Or, if you want to round 0.2345 to two decimal places, you need to round 23.45 (0.2345*100), then divide the result (23) by 100 to get 0.23.

In JavaScript code, that is simple to achieve:

Image for postView the raw code as a GitHub gist

Expanding this into a function with Math.pow(), we get:

Image for postView the raw code as a GitHub gist

A word to the wise: Beware rounding errors

You may be tempted to pass a negative number of decimal places to the round function to round on the other side of the decimal point. This seems to work fine, at first, until you run into a strange bug:

Image for postView the raw code as a GitHub gist

Unfortunately, you can actually run into the same issue with a positive number of decimal places, where 0.5 is occasionally rounded down instead of up, as you can see in the following example:

Image for postView the raw code as a GitHub gist

What just happened? Floating point math in JavaScript can produce rounding errors at times, as I discussed in my article in JavaScript in Plain English:

Why 0.1 + 0.2 ? 0.3 in JavaScript

JavaScript floating point math is a little off sometimes. Here?s why 0.1 + 0.2 ? 0.3 and what you can do if you need?

medium.com

Basically, floating point math is inherently a little off at times, based on the precision of the numbers being different in binary than in base-10.

The issue is that a programming language like JavaScript is prevented from making the numbers more precise by its specification. The ECMAScript specification clearly states that decimal point operations require floating point math, which has those rounding errors.

That means precise calculations can only be performed by integer values ? which is why you have fewer rounding errors when using a positive number of digits with the first round function above.

Thankfully Jack Moore has a better solution that prevents rounding errors at all, as he discusses in an article on his blog. Just use exponential notation when rounding to a certain number of decimal places in JavaScript:

Image for postView the raw code as a GitHub gist

If accuracy is important, which it probably is since you are trying to round to a certain precision, you should use the above code to round in JavaScript.

Rounding negative numbers in JavaScript

You should also be aware that negative numbers round differently than positive numbers in JavaScript. The docs for Math.round() explain it well, so I?ll let you read what they have to say:

?If the fractional portion of the argument is greater than 0.5, the argument is rounded to the integer with the next higher absolute value. If it is less than 0.5, the argument is rounded to the integer with the lower absolute value. If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +?.

Note that this differs from many languages? round() functions, which often round this case to the next integer away from zero, instead giving a different result in the case of negative numbers with a fractional part of exactly 0.5.? ? MDN Docs

In other words, -0.5 rounds to -0 (negative zero), not to -1 as you might expect, given that 0.5 rounds to 1:

Image for postView the raw code as a GitHub gist

If you want the usual behavior when rounding negative numbers, you would need to convert negative numbers to positive before calling Math.round(), and then convert them back to negative numbers before returning.

Conclusion

There is nothing too special about Math.round(), other than its odd behavior around the value -0.5 ? which may be JavaScript trivia or may be mission critical, depending on the use case.

For example, a program dealing with negative currency values may not want to round an expense of -$0.50 to $0 for consistency in accounting.

Otherwise, Math.round() is incredibly straightforward, which makes it convenient for rounding to a certain number of decimal places.

You just need to be aware of JavaScript?s inherent floating point rounding errors, which are usually not too serious. You can avoid rounding errors completely by using exponential notation when rounding.

This tutorial only addressed arithmetic rounding, not creating a string from a number using a certain number of decimal places. For information on doing so, please refer to the resources below in the Further Reading section.

Hopefully this has been helpful to you the next time you need to round a JavaScript floating point value to a certain number of decimals.

Happy coding! ?????????

Further Reading

  • Pawel Grzybek compares rounding to truncating numbers on his blog:

Rounding and truncating numbers in JavaScript | pawelgrzybek.com

Convert primary school math skills into code. Let’s put together all that we know about rounding and truncating numbers?

pawelgrzybek.com

  • John Au-Yeung covers many number methods in Better Programming:

The Ultimate Guide for Manipulating Numbers in JavaScript

Rounding Numbers

medium.com

  • Chris Ferdinandi talks about rounding and using delimiters on his blog:

How to round to the nearest number with vanilla JS

JavaScript has native methods for rounding numbers, but they only round floats (numbers with decimals) to the nearest?

gomakethings.com

  • The previously-mentioned math.js library has a rounding function:

math.js

Math.js is an extensive math library for JavaScript and Node.js. It features big numbers, complex numbers, matrices?

mathjs.org

  • MediaCollege has an alternative rounding algorithm using toFixed():

How to Round Numbers

This page shows you how to round a number to a specified number of decimal places. The example below shows numbers?

www.mediacollege.com

19

No Responses

Write a response