Rounding JavaScript Decimals

Jason Sturges
1 min readJul 18, 2020

--

Whether rounding decimals or dealing with roundoff errors, this utility function can help.

JavaScript numbers follow the IEEE-754 standard for double-precision floating-point arithmetic, with 64-bits of memory representing a wide range of numerical values by using a floating radix point.

An unfortunate phenomenon of this is rounding (or roundoff) errors, resulting in representation error of decimals.

Some examples:

0.1 + 1 - 1;  // equals: 0.10000000000000009
0.1 * 0.2; // equals: 0.020000000000000004
0.1 + 0.2; // equals: 0.30000000000000004

To work around this, and achieve a desired precision, this utility function rounds the specified number to a number of digits:

function roundDecimal(n, precision) {
var factor = Math.pow(10, precision);
return (Math.round(n * factor) / factor);
}

Let’s try that again:

roundDecimal(0.1 + 1 - 1, 1);  // returns: 0.1
roundDecimal(0.1 * 0.2, 2); // returns: 0.02
roundDecimal(0.1 + 0.2, 1); // returns: 0.3

This is also great for achieving a specific number of decimal precision:

const n = Math.PI;   // 3.141592653589793roundDecimal(n, 0);  // returns: 3
roundDecimal(n, 1); // returns: 3.1
roundDecimal(n, 2); // returns: 3.14
roundDecimal(n, 3); // returns: 3.142
roundDecimal(n, 4); // returns: 3.1416

--

--

Jason Sturges
Jason Sturges

Written by Jason Sturges

Avant-garde experimental artist — creative professional leveraging technology for immersive experiences

No responses yet