[javascript] Round to at most 2 decimal places (only if necessary)

I'd like to round at most 2 decimal places, but only if necessary.

Input:

10
1.7777777
9.1

Output:

10
1.78
9.1

How can I do this in JavaScript?

This question is related to javascript rounding decimal-point

The answer is


This answer is more about speed.

var precalculatedPrecisions = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10];

function round(num, _prec) {
    _precision = precalculatedPrecisions[_prec]
    return Math.round(num * _precision + 1e-14) / _precision ;
}

jsPerf about this.


Try to use the jQuery .number plug-in:

var number = 19.8000000007;
var res = 1 * $.number(number, 2);

I have found this works for all my use cases:

const round = (value, decimalPlaces = 0) => {
    const multiplier = Math.pow(10, decimalPlaces);
    return Math.round(value * multiplier + Number.EPSILON) / multiplier;
};

Keep in mind that is ES6. An ES5 equiv. would be very easy to code though so I'm not gonna add it.


There are a couple of ways to do that. For people like me, the Lodash's variant

function round(number, precision) {
    var pair = (number + 'e').split('e')
    var value = Math.round(pair[0] + 'e' + (+pair[1] + precision))
    pair = (value + 'e').split('e')
    return +(pair[0] + 'e' + (+pair[1] - precision))
}

Usage:

round(0.015, 2) // 0.02
round(1.005, 2) // 1.01

If your project uses jQuery or lodash, you can also find proper round method in the libraries.

Update 1

I removed the variant n.toFixed(2), because it is not correct. Thank you @avalanche1


the question is to rounds of 2 decimal.

let's not make this complicated modifying prototype chain etc..

here is one line solution

_x000D_
_x000D_
let round2dec = num => Math.round(num * 100) / 100; _x000D_
_x000D_
console.log(round2dec(1.77));_x000D_
console.log(round2dec(1.774));_x000D_
console.log(round2dec(1.777));_x000D_
console.log(round2dec(10));
_x000D_
_x000D_
_x000D_


A Generic Answer for all browsers and precisions:

function round(num, places) {
      if(!places){
       return Math.round(num);
      }

      var val = Math.pow(10, places);
      return Math.round(num * val) / val;
}

round(num, 2);

Mathematic floor and round definitions

enter image description here

lead us to

_x000D_
_x000D_
let round= x=> ( x+0.005 - (x+0.005)%0.01 +'' ).replace(/(\...)(.*)/,'$1');_x000D_
_x000D_
// for case like 1.384 we need to use regexp to get only 2 digits after dot_x000D_
// and cut off machine-error (epsilon)_x000D_
_x000D_
console.log(round(10));_x000D_
console.log(round(1.7777777));_x000D_
console.log(round(1.7747777));_x000D_
console.log(round(1.384));
_x000D_
_x000D_
_x000D_


Here is a function I came up with to do "round up". I used double Math.round to compensate for JavaScript's inaccurate multiplying, so 1.005 will be correctly rounded as 1.01.

function myRound(number, decimalplaces){
    if(decimalplaces > 0){
        var multiply1 = Math.pow(10,(decimalplaces + 4));
        var divide1 = Math.pow(10, decimalplaces);
        return Math.round(Math.round(number * multiply1)/10000 )/divide1;
    }
    if(decimalplaces < 0){
        var divide2 = Math.pow(10, Math.abs(decimalplaces));
        var multiply2 = Math.pow(10, Math.abs(decimalplaces));
        return Math.round(Math.round(number / divide2) * multiply2);
    }
    return Math.round(number);
}

A simpler ES6 way is

const round = (x, n) => 
  Number(parseFloat(Math.round(x * Math.pow(10, n)) / Math.pow(10, n)).toFixed(n));

This pattern also returns the precision asked for.

ex:

round(44.7826456, 4)  // yields 44.7826
round(78.12, 4)       // yields 78.12

Simple solution would be use lodash's ceil function if you want to round up...

https://lodash.com/docs/4.17.10#ceil

_.round(6.001,2)

gives 6

_.ceil(6.001, 2);

gives 6.01

_.ceil(37.4929,2);

gives 37.5

_.round(37.4929,2);

gives 37.49


To round at decimal positions pos (including no decimals) do Math.round(num * Math.pow(10,pos)) / Math.pow(10,pos)

_x000D_
_x000D_
var console = {_x000D_
 log: function(s) {_x000D_
  document.getElementById("console").innerHTML += s + "<br/>"_x000D_
 }_x000D_
}_x000D_
var roundDecimals=function(num,pos) {_x000D_
 return (Math.round(num * Math.pow(10,pos)) / Math.pow(10,pos) );_x000D_
}_x000D_
//https://en.wikipedia.org/wiki/Pi_x000D_
var pi=3.14159265358979323846264338327950288419716939937510;_x000D_
for(var i=2;i<15;i++) console.log("pi="+roundDecimals(pi,i));_x000D_
for(var i=15;i>=0;--i) console.log("pi="+roundDecimals(pi,i));
_x000D_
<div id="console" />
_x000D_
_x000D_
_x000D_


I was building a simple tipCalculator and there was a lot of answers here that seem to overcomplicate the issue. So I found summarizing the issue to be the best way to truly answer this question

if you want to create a rounded decimal number, first you call toFixed(# of decimal places you want to keep) and then wrap that in a Number()

so end result:

let amountDue = 286.44;
tip = Number((amountDue * 0.2).toFixed(2));
console.log(tip)  // 57.29 instead of 57.288

This worked pretty well for me when wanting to always round up to a certain decimal. The key here is that we will always be rounding up with the Math.ceil function.

You could conditionally select ceil or floor if needed.

_x000D_
_x000D_
     /**_x000D_
     * Possibility to lose precision at large numbers_x000D_
     * @param number_x000D_
     * @returns Number number_x000D_
     */_x000D_
    var roundUpToNearestHundredth = function(number) {_x000D_
_x000D_
        // Ensure that we use high precision Number_x000D_
        number = Number(number);_x000D_
_x000D_
        // Save the original number so when we extract the Hundredth decimal place we don't bit switch or lose precision_x000D_
        var numberSave = Number(number.toFixed(0));_x000D_
_x000D_
        // Remove the "integer" values off the top of the number_x000D_
        number = number - numberSave;_x000D_
_x000D_
        // Get the Hundredth decimal places_x000D_
        number *= 100;_x000D_
_x000D_
        // Ceil the decimals.  Therefore .15000001 will equal .151, etc._x000D_
        number = Math.ceil(number);_x000D_
_x000D_
        // Put the decimals back into their correct spot_x000D_
        number /= 100;_x000D_
_x000D_
        // Add the "integer" back onto the number_x000D_
        return number + numberSave;_x000D_
_x000D_
    };_x000D_
_x000D_
console.log(roundUpToNearestHundredth(6132423.1200000000001))
_x000D_
_x000D_
_x000D_


var roundUpto = function(number, upto){
    return Number(number.toFixed(upto));
}
roundUpto(0.1464676, 2);

toFixed(2) here 2 is number of digits upto which we want to round this num.


In general, decimal rounding is done by scaling: round(num * p) / p

Naive implementation

Using the following function with halfway numbers, you will get either the upper rounded value as expected, or the lower rounded value sometimes depending on the input.

This inconsistency in rounding may introduce hard to detect bugs in the client code.

_x000D_
_x000D_
function naiveRound(num, decimalPlaces = 0) {
    var p = Math.pow(10, decimalPlaces);
    return Math.round(num * p) / p;
}

console.log( naiveRound(1.245, 2) );  // 1.25 correct (rounded as expected)
console.log( naiveRound(1.255, 2) );  // 1.25 incorrect (should be 1.26)

// testing edge cases
console.log( naiveRound(1.005, 2) );  // 1    incorrect (should be 1.01)
console.log( naiveRound(2.175, 2) );  // 2.17 incorrect (should be 2.18)
console.log( naiveRound(5.015, 2) );  // 5.01 incorrect (should be 5.02)
_x000D_
_x000D_
_x000D_

Better implementations

Exponential notation

By converting the number to a string in the exponential notation, positive numbers are rounded as expected. But, be aware that negative numbers round differently than positive numbers.

In fact, it performs what is basically equivalent to "round half up" as the rule, you will see that round(-1.005, 2) evaluates to -1 even though round(1.005, 2) evaluates to 1.01. The lodash _.round method uses this technique.

_x000D_
_x000D_
/**
 * Round half up ('round half towards positive infinity')
 * Uses exponential notation to avoid floating-point issues.
 * Negative numbers round differently than positive numbers.
 */
function round(num, decimalPlaces = 0) {
    num = Math.round(num + "e" + decimalPlaces);
    return Number(num + "e" + -decimalPlaces);
}

// test rounding of half
console.log( round(0.5, 0) );  // 1
console.log( round(-0.5, 0) ); // 0

// testing edge cases
console.log( round(1.005, 2) );   // 1.01
console.log( round(2.175, 2) );   // 2.18
console.log( round(5.015, 2) );   // 5.02

console.log( round(-1.005, 2) );  // -1
console.log( round(-2.175, 2) );  // -2.17
console.log( round(-5.015, 2) );  // -5.01
_x000D_
_x000D_
_x000D_

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.

// Round half away from zero
function round(num, decimalPlaces = 0) {
    num = Math.round(Math.abs(num) + "e" + decimalPlaces) * Math.sign(num);
    return Number(num + "e" + -decimalPlaces);
}

Number.EPSILON

There is a different purely mathematical technique to perform round-to-nearest (using "round half away from zero"), in which epsilon correction is applied before calling the rounding function.

Simply, we add the smallest possible float value (= 1.0 ulp; unit in the last place) to the product before rounding. This moves to the next representable float value, away from zero.

_x000D_
_x000D_
/**
 * Round half away from zero ('commercial' rounding)
 * Uses correction to offset floating-point inaccuracies.
 * Works symmetrically for positive and negative numbers.
 */
function round(num, decimalPlaces = 0) {
    var p = Math.pow(10, decimalPlaces);
    var m = (num * p) * (1 + Number.EPSILON);
    return Math.round(m) / p;
}

// test rounding of half
console.log( round(0.5, 0) );  // 1
console.log( round(-0.5, 0) ); // -1

// testing edge cases
console.log( round(1.005, 2) );  // 1.01
console.log( round(2.175, 2) );  // 2.18
console.log( round(5.015, 2) );  // 5.02

console.log( round(-1.005, 2) ); // -1.01
console.log( round(-2.175, 2) ); // -2.18
console.log( round(-5.015, 2) ); // -5.02
_x000D_
_x000D_
_x000D_

This is needed to offset the implicit round-off error that may occur during encoding of decimal numbers, particularly those having "5" in the last decimal position, like 1.005, 2.675 and 16.235. Actually, 1.005 in decimal system is encoded to 1.0049999999999999 in 64-bit binary float; while, 1234567.005 in decimal system is encoded to 1234567.0049999998882413 in 64-bit binary float.

It is worth noting that the maximum binary round-off error is dependent upon (1) the magnitude of the number and (2) the relative machine epsilon (2^-52).

Double rounding

Here, we use the toPrecision() method to strip the floating-point round-off errors in the intermediate calculations. Simply, we round to 15 significant figures to strip the round-off error at the 16th significant digit. This technique to preround the result to significant digits is also used by PHP 7 round function.

_x000D_
_x000D_
// Round half away from zero
function round(num, decimalPlaces = 0) {
    var p = Math.pow(10, decimalPlaces);
    var m = Number((Math.abs(num) * p).toPrecision(15));
    return Math.round(m) / p * Math.sign(num);
}

// test rounding of half
console.log( round(0.5, 0) );  // 1
console.log( round(-0.5, 0) ); // -1

// testing edge cases
console.log( round(1.005, 2) );  // 1.01
console.log( round(2.175, 2) );  // 2.18
console.log( round(5.015, 2) );  // 5.02

console.log( round(-1.005, 2) ); // -1.01
console.log( round(-2.175, 2) ); // -2.18
console.log( round(-5.015, 2) ); // -5.02
_x000D_
_x000D_
_x000D_

Arbitrary-precision JavaScript library - decimal.js

_x000D_
_x000D_
// Round half away from zero
function round(num, decimalPlaces = 0) {
    return new Decimal(num).toDecimalPlaces(decimalPlaces).toNumber();
}

// test rounding of half
console.log( round(0.5, 0) );  // 1
console.log( round(-0.5, 0) ); // -1

// testing edge cases
console.log( round(1.005, 2) );  // 1.01
console.log( round(2.175, 2) );  // 2.18
console.log( round(5.015, 2) );  // 5.02

console.log( round(-1.005, 2) ); // -1.01
console.log( round(-2.175, 2) ); // -2.18
console.log( round(-5.015, 2) ); // -5.02
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/10.2.1/decimal.js" integrity="sha512-GKse2KVGCCMVBn4riigHjXE8j5hCxYLPXDw8AvcjUtrt+a9TbZFtIKGdArXwYOlZvdmkhQLWQ46ZE3Q1RIa7uQ==" crossorigin="anonymous"></script>
_x000D_
_x000D_
_x000D_

Solution 1: string in exponential notation

Inspired by the solution provided by KFish here: https://stackoverflow.com/a/55521592/4208440

A simple drop in solution that provides accurate decimal rounding, flooring, and ceiling to a specific number of decimal places without adding a whole library. It treats floats more like decimals by fixing the binary rounding issues to avoid unexpected results: for example, floor((0.1+0.7)*10) will return the expected result 8.

Numbers are rounded to a specific number of fractional digits. Specifying a negative precision will round to any number of places to the left of the decimal point.

_x000D_
_x000D_
// Solution 1
var DecimalPrecision = (function() {
    if (Math.sign === undefined) {
        Math.sign = function(x) {
            return ((x > 0) - (x < 0)) || +x;
        };
    }
    if (Math.trunc === undefined) {
        Math.trunc = function(v) {
            return v < 0 ? Math.ceil(v) : Math.floor(v);
        };
    }
    var decimalAdjust = function(type, num, decimalPlaces) {
        var shift = function(value, exponent) {
            value = (value + 'e').split('e');
            return +(value[0] + 'e' + (+value[1] + (exponent || 0)));
        };
        var n = type === 'round' ? Math.abs(num) : num;
        var m = shift(n, +decimalPlaces);
        var r = shift(Math[type](m), -decimalPlaces);
        return type === 'round' ? Math.sign(num) * r : r;
    };
    return {
        // Decimal round (half away from zero)
        round: function(num, decimalPlaces) {
            return decimalAdjust('round', num, decimalPlaces);
        },
        // Decimal ceil
        ceil: function(num, decimalPlaces) {
            return decimalAdjust('ceil', num, decimalPlaces);
        },
        // Decimal floor
        floor: function(num, decimalPlaces) {
            return decimalAdjust('floor', num, decimalPlaces);
        },
        // Decimal trunc
        trunc: function(num, decimalPlaces) {
            return decimalAdjust('trunc', num, decimalPlaces);
        },
        // Format using fixed-point notation
        toFixed: function(num, decimalPlaces) {
            return decimalAdjust('round', num, decimalPlaces).toFixed(decimalPlaces);
        }
    };
})();

// test rounding of half
console.log(DecimalPrecision.round(0.5));  // 1
console.log(DecimalPrecision.round(-0.5)); // -1

// testing very small numbers
console.log(DecimalPrecision.ceil(1e-8, 2) === 0.01);         // 0.01
console.log(DecimalPrecision.floor(1e-8, 2) === 0);              // 0

// testing simple cases
console.log(DecimalPrecision.round(5.12, 1) === 5.1);          // 5.1
console.log(DecimalPrecision.round(-5.12, 1) === -5.1);       // -5.1
console.log(DecimalPrecision.ceil(5.12, 1) === 5.2);           // 5.2
console.log(DecimalPrecision.ceil(-5.12, 1) === -5.1);        // -5.1
console.log(DecimalPrecision.floor(5.12, 1) === 5.1);          // 5.1
console.log(DecimalPrecision.floor(-5.12, 1) === -5.2);       // -5.2
console.log(DecimalPrecision.trunc(5.12, 1) === 5.1);          // 5.1
console.log(DecimalPrecision.trunc(-5.12, 1) === -5.1);       // -5.1

// testing edge cases for round
console.log(DecimalPrecision.round(1.005, 2) === 1.01);       // 1.01
console.log(DecimalPrecision.round(39.425, 2) === 39.43);    // 39.43
console.log(DecimalPrecision.round(-1.005, 2) === -1.01);    // -1.01
console.log(DecimalPrecision.round(-39.425, 2) === -39.43); // -39.43

// testing edge cases for ceil
console.log(DecimalPrecision.ceil(9.130, 2) === 9.13);        // 9.13
console.log(DecimalPrecision.ceil(65.180, 2) === 65.18);     // 65.18
console.log(DecimalPrecision.ceil(-2.260, 2) === -2.26);     // -2.26
console.log(DecimalPrecision.ceil(-18.150, 2) === -18.15);  // -18.15

// testing edge cases for floor
console.log(DecimalPrecision.floor(2.260, 2) === 2.26);       // 2.26
console.log(DecimalPrecision.floor(18.150, 2) === 18.15);    // 18.15
console.log(DecimalPrecision.floor(-9.130, 2) === -9.13);    // -9.13
console.log(DecimalPrecision.floor(-65.180, 2) === -65.18); // -65.18

// testing edge cases for trunc
console.log(DecimalPrecision.trunc(2.260, 2) === 2.26);       // 2.26
console.log(DecimalPrecision.trunc(18.150, 2) === 18.15);    // 18.15
console.log(DecimalPrecision.trunc(-2.260, 2) === -2.26);    // -2.26
console.log(DecimalPrecision.trunc(-18.150, 2) === -18.15); // -18.15

// testing round to tens and hundreds
console.log(DecimalPrecision.round(1262.48, -1) === 1260);    // 1260
console.log(DecimalPrecision.round(1262.48, -2) === 1300);    // 1300

// testing toFixed()
console.log(DecimalPrecision.toFixed(1.005, 2) === "1.01");   // "1.01"
_x000D_
_x000D_
_x000D_

Solution 2: purely mathematical (Number.EPSILON)

This solution avoids any string conversion / manipulation of any kind for performance reasons.

Solution 1: 25,838 ops/sec

Solution 2: 655,087 ops/sec

http://jsbench.github.io/#31ec3a8b3d22bd840f8e6822e681a3ac

_x000D_
_x000D_
// Solution 2
var DecimalPrecision2 = (function() {
    if (Number.EPSILON === undefined) {
        Number.EPSILON = Math.pow(2, -52);
    }
    if (Math.trunc === undefined) {
        Math.trunc = function(v) {
            return v < 0 ? Math.ceil(v) : Math.floor(v);
        };
    }
    var isRound = function(num, decimalPlaces) {
        //return decimalPlaces >= 0 &&
        //    +num.toFixed(decimalPlaces) === num;
        var p = Math.pow(10, decimalPlaces);
        return Math.round(num * p) / p === num;
    };
    var decimalAdjust = function(type, num, decimalPlaces) {
        if (isRound(num, decimalPlaces || 0))
            return num;
        var p = Math.pow(10, decimalPlaces || 0);
        var m = (num * p) * (1 + Number.EPSILON);
        return Math[type](m) / p;
    };
    return {
        // Decimal round (half away from zero)
        round: function(num, decimalPlaces) {
            return decimalAdjust('round', num, decimalPlaces);
        },
        // Decimal ceil
        ceil: function(num, decimalPlaces) {
            return decimalAdjust('ceil', num, decimalPlaces);
        },
        // Decimal floor
        floor: function(num, decimalPlaces) {
            return decimalAdjust('floor', num, decimalPlaces);
        },
        // Decimal trunc
        trunc: function(num, decimalPlaces) {
            return decimalAdjust('trunc', num, decimalPlaces);
        },
        // Format using fixed-point notation
        toFixed: function(num, decimalPlaces) {
            return decimalAdjust('round', num, decimalPlaces).toFixed(decimalPlaces);
        }
    };
})();

// test rounding of half
console.log(DecimalPrecision2.round(0.5));  // 1
console.log(DecimalPrecision2.round(-0.5)); // -1

// testing very small numbers
console.log(DecimalPrecision2.ceil(1e-8, 2) === 0.01);         // 0.01
console.log(DecimalPrecision2.floor(1e-8, 2) === 0);              // 0

// testing simple cases
console.log(DecimalPrecision2.round(5.12, 1) === 5.1);          // 5.1
console.log(DecimalPrecision2.round(-5.12, 1) === -5.1);       // -5.1
console.log(DecimalPrecision2.ceil(5.12, 1) === 5.2);           // 5.2
console.log(DecimalPrecision2.ceil(-5.12, 1) === -5.1);        // -5.1
console.log(DecimalPrecision2.floor(5.12, 1) === 5.1);          // 5.1
console.log(DecimalPrecision2.floor(-5.12, 1) === -5.2);       // -5.2
console.log(DecimalPrecision2.trunc(5.12, 1) === 5.1);          // 5.1
console.log(DecimalPrecision2.trunc(-5.12, 1) === -5.1);       // -5.1

// testing edge cases for round
console.log(DecimalPrecision2.round(1.005, 2) === 1.01);       // 1.01
console.log(DecimalPrecision2.round(39.425, 2) === 39.43);    // 39.43
console.log(DecimalPrecision2.round(-1.005, 2) === -1.01);    // -1.01
console.log(DecimalPrecision2.round(-39.425, 2) === -39.43); // -39.43

// testing edge cases for ceil
console.log(DecimalPrecision2.ceil(9.130, 2) === 9.13);        // 9.13
console.log(DecimalPrecision2.ceil(65.180, 2) === 65.18);     // 65.18
console.log(DecimalPrecision2.ceil(-2.260, 2) === -2.26);     // -2.26
console.log(DecimalPrecision2.ceil(-18.150, 2) === -18.15);  // -18.15

// testing edge cases for floor
console.log(DecimalPrecision2.floor(2.260, 2) === 2.26);       // 2.26
console.log(DecimalPrecision2.floor(18.150, 2) === 18.15);    // 18.15
console.log(DecimalPrecision2.floor(-9.130, 2) === -9.13);    // -9.13
console.log(DecimalPrecision2.floor(-65.180, 2) === -65.18); // -65.18

// testing edge cases for trunc
console.log(DecimalPrecision2.trunc(2.260, 2) === 2.26);       // 2.26
console.log(DecimalPrecision2.trunc(18.150, 2) === 18.15);    // 18.15
console.log(DecimalPrecision2.trunc(-2.260, 2) === -2.26);    // -2.26
console.log(DecimalPrecision2.trunc(-18.150, 2) === -18.15); // -18.15

// testing round to tens and hundreds
console.log(DecimalPrecision2.round(1262.48, -1) === 1260);    // 1260
console.log(DecimalPrecision2.round(1262.48, -2) === 1300);    // 1300

// testing toFixed()
console.log(DecimalPrecision2.toFixed(1.005, 2) === "1.01");   // "1.01"
_x000D_
_x000D_
_x000D_

Solution 3: double rounding

This solution uses the toPrecision() method to strip the floating-point round-off errors.

_x000D_
_x000D_
// Solution 3
var DecimalPrecision3 = (function() {
    if (Math.sign === undefined) {
        Math.sign = function(x) {
            return ((x > 0) - (x < 0)) || +x;
        };
    }
    if (Math.trunc === undefined) {
        Math.trunc = function(v) {
            return v < 0 ? Math.ceil(v) : Math.floor(v);
        };
    }
    // Eliminate binary floating-point inaccuracies.
    var stripError = function(num) {
        if (Number.isInteger(num))
            return num;
        return parseFloat(num.toPrecision(15));
    };
    var decimalAdjust = function(type, num, decimalPlaces) {
        var n = type === 'round' ? Math.abs(num) : num;
        var p = Math.pow(10, decimalPlaces || 0);
        var m = stripError(n * p);
        var r = Math[type](m) / p;
        return type === 'round' ? Math.sign(num) * r : r;
    };
    return {
        // Decimal round (half away from zero)
        round: function(num, decimalPlaces) {
            return decimalAdjust('round', num, decimalPlaces);
        },
        // Decimal ceil
        ceil: function(num, decimalPlaces) {
            return decimalAdjust('ceil', num, decimalPlaces);
        },
        // Decimal floor
        floor: function(num, decimalPlaces) {
            return decimalAdjust('floor', num, decimalPlaces);
        },
        // Decimal trunc
        trunc: function(num, decimalPlaces) {
            return decimalAdjust('trunc', num, decimalPlaces);
        },
        // Format using fixed-point notation
        toFixed: function(num, decimalPlaces) {
            return decimalAdjust('round', num, decimalPlaces).toFixed(decimalPlaces);
        }
    };
})();

// test rounding of half
console.log(DecimalPrecision3.round(0.5));  // 1
console.log(DecimalPrecision3.round(-0.5)); // -1

// testing very small numbers
console.log(DecimalPrecision3.ceil(1e-8, 2) === 0.01);         // 0.01
console.log(DecimalPrecision3.floor(1e-8, 2) === 0);              // 0

// testing simple cases
console.log(DecimalPrecision3.round(5.12, 1) === 5.1);          // 5.1
console.log(DecimalPrecision3.round(-5.12, 1) === -5.1);       // -5.1
console.log(DecimalPrecision3.ceil(5.12, 1) === 5.2);           // 5.2
console.log(DecimalPrecision3.ceil(-5.12, 1) === -5.1);        // -5.1
console.log(DecimalPrecision3.floor(5.12, 1) === 5.1);          // 5.1
console.log(DecimalPrecision3.floor(-5.12, 1) === -5.2);       // -5.2
console.log(DecimalPrecision3.trunc(5.12, 1) === 5.1);          // 5.1
console.log(DecimalPrecision3.trunc(-5.12, 1) === -5.1);       // -5.1

// testing edge cases for round
console.log(DecimalPrecision3.round(1.005, 2) === 1.01);       // 1.01
console.log(DecimalPrecision3.round(39.425, 2) === 39.43);    // 39.43
console.log(DecimalPrecision3.round(-1.005, 2) === -1.01);    // -1.01
console.log(DecimalPrecision3.round(-39.425, 2) === -39.43); // -39.43

// testing edge cases for ceil
console.log(DecimalPrecision3.ceil(9.130, 2) === 9.13);        // 9.13
console.log(DecimalPrecision3.ceil(65.180, 2) === 65.18);     // 65.18
console.log(DecimalPrecision3.ceil(-2.260, 2) === -2.26);     // -2.26
console.log(DecimalPrecision3.ceil(-18.150, 2) === -18.15);  // -18.15

// testing edge cases for floor
console.log(DecimalPrecision3.floor(2.260, 2) === 2.26);       // 2.26
console.log(DecimalPrecision3.floor(18.150, 2) === 18.15);    // 18.15
console.log(DecimalPrecision3.floor(-9.130, 2) === -9.13);    // -9.13
console.log(DecimalPrecision3.floor(-65.180, 2) === -65.18); // -65.18

// testing edge cases for trunc
console.log(DecimalPrecision3.trunc(2.260, 2) === 2.26);       // 2.26
console.log(DecimalPrecision3.trunc(18.150, 2) === 18.15);    // 18.15
console.log(DecimalPrecision3.trunc(-2.260, 2) === -2.26);    // -2.26
console.log(DecimalPrecision3.trunc(-18.150, 2) === -18.15); // -18.15

// testing round to tens and hundreds
console.log(DecimalPrecision3.round(1262.48, -1) === 1260);    // 1260
console.log(DecimalPrecision3.round(1262.48, -2) === 1300);    // 1300

// testing toFixed()
console.log(DecimalPrecision3.toFixed(1.005, 2) === "1.01");   // "1.01"
_x000D_
_x000D_
_x000D_

Solution 4: double rounding v2

This solution is just like Solution 3, however it uses a custom toPrecision() function.

_x000D_
_x000D_
// Solution 4
var DecimalPrecision4 = (function() {
    if (Math.sign === undefined) {
        Math.sign = function(x) {
            return ((x > 0) - (x < 0)) || +x;
        };
    }
    if (Math.trunc === undefined) {
        Math.trunc = function(v) {
            return v < 0 ? Math.ceil(v) : Math.floor(v);
        };
    }
    var toPrecision = function(num, significantDigits) {
        // Return early for ±0, NaN and Infinity.
        if (!num || !Number.isFinite(num))
            return num;
        // Compute shift of the decimal point.
        var shift = significantDigits - 1 - Math.floor(Math.log10(Math.abs(num)));
        // Return if rounding to the same or higher precision.
        var decimalPlaces = 0;
        for (var p = 1; !Number.isInteger(num * p); p *= 10) decimalPlaces++;
        if (shift >= decimalPlaces)
            return num;
        // Round to sf-1 fractional digits of normalized mantissa x.dddd
        var scale = Math.pow(10, Math.abs(shift));
        return shift > 0 ?
            Math.round(num * scale) / scale :
            Math.round(num / scale) * scale;
    };
    // Eliminate binary floating-point inaccuracies.
    var stripError = function(num) {
        if (Number.isInteger(num))
            return num;
        return toPrecision(num, 15);
    };
    var decimalAdjust = function(type, num, decimalPlaces) {
        var n = type === 'round' ? Math.abs(num) : num;
        var p = Math.pow(10, decimalPlaces || 0);
        var m = stripError(n * p);
        var r = Math[type](m) / p;
        return type === 'round' ? Math.sign(num) * r : r;
    };
    return {
        // Decimal round (half away from zero)
        round: function(num, decimalPlaces) {
            return decimalAdjust('round', num, decimalPlaces);
        },
        // Decimal ceil
        ceil: function(num, decimalPlaces) {
            return decimalAdjust('ceil', num, decimalPlaces);
        },
        // Decimal floor
        floor: function(num, decimalPlaces) {
            return decimalAdjust('floor', num, decimalPlaces);
        },
        // Decimal trunc
        trunc: function(num, decimalPlaces) {
            return decimalAdjust('trunc', num, decimalPlaces);
        },
        // Format using fixed-point notation
        toFixed: function(num, decimalPlaces) {
            return decimalAdjust('round', num, decimalPlaces).toFixed(decimalPlaces);
        }
    };
})();

// test rounding of half
console.log(DecimalPrecision4.round(0.5));  // 1
console.log(DecimalPrecision4.round(-0.5)); // -1

// testing very small numbers
console.log(DecimalPrecision4.ceil(1e-8, 2) === 0.01);         // 0.01
console.log(DecimalPrecision4.floor(1e-8, 2) === 0);              // 0

// testing simple cases
console.log(DecimalPrecision4.round(5.12, 1) === 5.1);          // 5.1
console.log(DecimalPrecision4.round(-5.12, 1) === -5.1);       // -5.1
console.log(DecimalPrecision4.ceil(5.12, 1) === 5.2);           // 5.2
console.log(DecimalPrecision4.ceil(-5.12, 1) === -5.1);        // -5.1
console.log(DecimalPrecision4.floor(5.12, 1) === 5.1);          // 5.1
console.log(DecimalPrecision4.floor(-5.12, 1) === -5.2);       // -5.2
console.log(DecimalPrecision4.trunc(5.12, 1) === 5.1);          // 5.1
console.log(DecimalPrecision4.trunc(-5.12, 1) === -5.1);       // -5.1

// testing edge cases for round
console.log(DecimalPrecision4.round(1.005, 2) === 1.01);       // 1.01
console.log(DecimalPrecision4.round(39.425, 2) === 39.43);    // 39.43
console.log(DecimalPrecision4.round(-1.005, 2) === -1.01);    // -1.01
console.log(DecimalPrecision4.round(-39.425, 2) === -39.43); // -39.43

// testing edge cases for ceil
console.log(DecimalPrecision4.ceil(9.130, 2) === 9.13);        // 9.13
console.log(DecimalPrecision4.ceil(65.180, 2) === 65.18);     // 65.18
console.log(DecimalPrecision4.ceil(-2.260, 2) === -2.26);     // -2.26
console.log(DecimalPrecision4.ceil(-18.150, 2) === -18.15);  // -18.15

// testing edge cases for floor
console.log(DecimalPrecision4.floor(2.260, 2) === 2.26);       // 2.26
console.log(DecimalPrecision4.floor(18.150, 2) === 18.15);    // 18.15
console.log(DecimalPrecision4.floor(-9.130, 2) === -9.13);    // -9.13
console.log(DecimalPrecision4.floor(-65.180, 2) === -65.18); // -65.18

// testing edge cases for trunc
console.log(DecimalPrecision4.trunc(2.260, 2) === 2.26);       // 2.26
console.log(DecimalPrecision4.trunc(18.150, 2) === 18.15);    // 18.15
console.log(DecimalPrecision4.trunc(-2.260, 2) === -2.26);    // -2.26
console.log(DecimalPrecision4.trunc(-18.150, 2) === -18.15); // -18.15

// testing round to tens and hundreds
console.log(DecimalPrecision4.round(1262.48, -1) === 1260);    // 1260
console.log(DecimalPrecision4.round(1262.48, -2) === 1300);    // 1300

// testing toFixed()
console.log(DecimalPrecision4.toFixed(1.005, 2) === "1.01");   // "1.01"
_x000D_
_x000D_
_x000D_

Benchmarks

http://jsbench.github.io/#31ec3a8b3d22bd840f8e6822e681a3ac

Here is a benchmark comparing the operations per second in the solutions above on Chrome 85.0.4183.83. Obviously all browsers differ, so your mileage may vary.

Benchmark comparison (Note: More is better)

Thanks @Mike for adding a screenshot of the benchmark.


I created this function, for rounding a number. The value can be a string (ex. '1.005') or a number 1.005 that will be 1 by default and if you specify the decimal to be 2, the result will be 1.01

round(value: string | number, decimals: number | string = "0"): number | null {
    return +( Math.round(Number(value + "e+"+decimals)) + "e-" + decimals);
}

Usage: round(1.005, 2) // 1.01 or Usage: round('1.005', 2) //1.01


You should use:

Math.round( num * 100 + Number.EPSILON ) / 100

No one seems to be aware of Number.EPSILON.

Also it's worth noting that this is not a JavaScript weirdness like some people stated.

That is simply the way floating point numbers works in a computer. Like 99% of programming languages, JavaScript doesn't have home made floating point numbers; it relies on the CPU/FPU for that. A computer uses binary, and in binary, there isn't any numbers like 0.1, but a mere binary approximation for that. Why? For the same reason than 1/3 cannot be written in decimal: its value is 0.33333333... with an infinity of threes.

Here come Number.EPSILON. That number is the difference between 1 and the next number existing in the double precision floating point numbers. That's it: There is no number between 1 and 1 + Number.EPSILON.

EDIT:

As asked in the comments, let's clarify one thing: adding Number.EPSILON is relevant only when the value to round is the result of an arithmetic operation, as it can swallow some floating point error delta.

It's not useful when the value comes from a direct source (e.g.: literal, user input or sensor).

EDIT (2019):

Like @maganap and some peoples have pointed out, it's best to add Number.EPSILON before multiplying:

Math.round( ( num + Number.EPSILON ) * 100 ) / 100

EDIT (december 2019):

Lately, I use a function similar to this one for comparing numbers epsilon-aware:

const ESPILON_RATE = 1 + Number.EPSILON ;
const ESPILON_ZERO = Number.MIN_VALUE ;

function epsilonEquals( a , b ) {
  if ( Number.isNaN( a ) || Number.isNaN( b ) ) {
    return false ;
  }
  if ( a === 0 || b === 0 ) {
    return a <= b + EPSILON_ZERO && b <= a + EPSILON_ZERO ;
  }
  return a <= b * EPSILON_RATE && b <= a * EPSILON_RATE ;
}

My use-case is an assertion + data validation lib I'm developing for many years.

In fact, in the code I'm using ESPILON_RATE = 1 + 4 * Number.EPSILON and EPSILON_ZERO = 4 * Number.MIN_VALUE (four times the epsilon), because I want an equality checker loose enough for cumulating floating point error.

So far, it looks perfect for me. I hope it will help.


I reviewed every answer of this post. Here is my take on the matter:

_x000D_
_x000D_
const nbRounds = 7;
const round = (x, n=2) => {
    const precision = Math.pow(10, n)
    return Math.round((x+Number.EPSILON) * precision ) / precision;
}

new Array(nbRounds).fill(1).forEach((_,i)=> {
    console.log("round(1.00083899, ",i+1,") > ", round(1.00083899, i+1))
    console.log("round(1.83999305, ",i+1,") > ", round(1.83999305, i+1))
})
_x000D_
_x000D_
_x000D_


Here is a simple way to do it:

Math.round(value * 100) / 100

You might want to go ahead and make a separate function to do it for you though:

function roundToTwo(value) {
    return(Math.round(value * 100) / 100);
}

Then you would simply pass in the value.

You could enhance it to round to any arbitrary number of decimals by adding a second parameter.

function myRound(value, places) {
    var multiplier = Math.pow(10, places);

    return (Math.round(value * multiplier) / multiplier);
}

I tried my very own code, try this

function AmountDispalyFormat(value) {
    value = value.toFixed(3);
    var amount = value.toString().split('.');
    var result = 0;
    if (amount.length > 1) {
        var secondValue = parseInt(amount[1].toString().slice(0, 2));
        if (amount[1].toString().length > 2) {
            if (parseInt(amount[1].toString().slice(2, 3)) > 4) {
                secondValue++;
                if (secondValue == 100) {
                    amount[0] = parseInt(amount[0]) + 1;
                    secondValue = 0;
                }
            }
        }

        if (secondValue.toString().length == 1) {
            secondValue = "0" + secondValue;
        }
        result = parseFloat(amount[0] + "." + secondValue);
    } else {
        result = parseFloat(amount);
    }
    return result;
}

Consider .toFixed() and .toPrecision():

http://www.javascriptkit.com/javatutors/formatnumber.shtml


This may help you:

var result = Math.round(input*100)/100;

for more information, you can have a look at this link

Math.round(num) vs num.toFixed(0) and browser inconsistencies


Node.js

This did the trick for me on Node.js in a matter of seconds:

npm install math

Source: http://mathjs.org/examples/basic_usage.js.html


As per the answer already given in comment with the link to http://jsfiddle.net/AsRqx/ Following one worked for me perfectly.

function C(num) 
  { return +(Math.round(num + "e+2")  + "e-2");
  }

function N(num, places) 
  { return +(Math.round(num + "e+" + places)  + "e-" + places);
  }

C(1.005);

N(1.005,0);
N(1.005,1); //up to 1 decimal places
N(1.005,2); //up to 2 decimal places
N(1.005,3); //up to 3 decimal places

I'll add one more approach to this.

number = 16.6666666;
console.log(parseFloat(number.toFixed(2)));
"16.67"

number = 16.6;
console.log(parseFloat(number.toFixed(2)));
"16.6"

number = 16;
console.log(parseFloat(number.toFixed(2)));
"16"

.toFixed(2) returns a string with exactily 2 decimal points, that may or may not be trailing zeros. Doing a parseFloat() will eliminate those trailing zeros.


One can use .toFixed(NumberOfDecimalPlaces).

var str = 10.234.toFixed(2); // => '10.23'
var number = Number(str); // => 10.23

This is the simplest, more elegant solution (and I am the best of the world;):

function roundToX(num, X) {    
    return +(Math.round(num + "e+"+X)  + "e-"+X);
}
//roundToX(66.66666666,2) => 66.67
//roundToX(10,2) => 10
//roundToX(10.904,2) => 10.9

Keep type as integer for later sorting or other math operations:

Math.round(1.7777777 * 100)/100

1.78

// Round up!
Math.ceil(1.7777777 * 100)/100 

1.78

// Round down!
Math.floor(1.7777777 * 100)/100

1.77

Or convert to string:

(1.7777777).toFixed(2)

"1.77"


This question is complicated.

Suppose we have a function, roundTo2DP(num), that takes a float as an argument and returns a value rounded to 2 decimal places. What should each of these expressions evaluate to?

  • roundTo2DP(0.014999999999999999)
  • roundTo2DP(0.0150000000000000001)
  • roundTo2DP(0.015)

The 'obvious' answer is that the first example should round to 0.01 (because it's closer to 0.01 than to 0.02) while the other two should round to 0.02 (because 0.0150000000000000001 is closer to 0.02 than to 0.01, and because 0.015 is exactly halfway between them and there is a mathematical convention that such numbers get rounded up).

The catch, which you may have guessed, is that roundTo2DP cannot possibly be implemented to give those obvious answers, because all three numbers passed to it are the same number. IEEE 754 binary floating point numbers (the kind used by JavaScript) can't exactly represent most non-integer numbers, and so all three numeric literals above get rounded to a nearby valid floating point number. This number, as it happens, is exactly

0.01499999999999999944488848768742172978818416595458984375

which is closer to 0.01 than to 0.02.

You can see that all three numbers are the same at your browser console, Node shell, or other JavaScript interpreter. Just compare them:

> 0.014999999999999999 === 0.0150000000000000001
true

So when I write m = 0.0150000000000000001, the exact value of m that I end up with is closer to 0.01 than it is to 0.02. And yet, if I convert m to a String...

> var m = 0.0150000000000000001;
> console.log(String(m));
0.015
> var m = 0.014999999999999999;
> console.log(String(m));
0.015

... I get 0.015, which should round to 0.02, and which is noticeably not the 56-decimal-place number I earlier said that all of these numbers were exactly equal to. So what dark magic is this?

The answer can be found in the ECMAScript specification, in section 7.1.12.1: ToString applied to the Number type. Here the rules for converting some Number m to a String are laid down. The key part is point 5, in which an integer s is generated whose digits will be used in the String representation of m:

let n, k, and s be integers such that k = 1, 10k-1 = s < 10k, the Number value for s × 10n-k is m, and k is as small as possible. Note that k is the number of digits in the decimal representation of s, that s is not divisible by 10, and that the least significant digit of s is not necessarily uniquely determined by these criteria.

The key part here is the requirement that "k is as small as possible". What that requirement amounts to is a requirement that, given a Number m, the value of String(m) must have the least possible number of digits while still satisfying the requirement that Number(String(m)) === m. Since we already know that 0.015 === 0.0150000000000000001, it's now clear why String(0.0150000000000000001) === '0.015' must be true.

Of course, none of this discussion has directly answered what roundTo2DP(m) should return. If m's exact value is 0.01499999999999999944488848768742172978818416595458984375, but its String representation is '0.015', then what is the correct answer - mathematically, practically, philosophically, or whatever - when we round it to two decimal places?

There is no single correct answer to this. It depends upon your use case. You probably want to respect the String representation and round upwards when:

  • The value being represented is inherently discrete, e.g. an amount of currency in a 3-decimal-place currency like dinars. In this case, the true value of a Number like 0.015 is 0.015, and the 0.0149999999... representation that it gets in binary floating point is a rounding error. (Of course, many will argue, reasonably, that you should use a decimal library for handling such values and never represent them as binary floating point Numbers in the first place.)
  • The value was typed by a user. In this case, again, the exact decimal number entered is more 'true' than the nearest binary floating point representation.

On the other hand, you probably want to respect the binary floating point value and round downwards when your value is from an inherently continuous scale - for instance, if it's a reading from a sensor.

These two approaches require different code. To respect the String representation of the Number, we can (with quite a bit of reasonably subtle code) implement our own rounding that acts directly on the String representation, digit by digit, using the same algorithm you would've used in school when you were taught how to round numbers. Below is an example which respects the OP's requirement of representing the number to 2 decimal places "only when necessary" by stripping trailing zeroes after the decimal point; you may, of course, need to tweak it to your precise needs.

/**
 * Converts num to a decimal string (if it isn't one already) and then rounds it
 * to at most dp decimal places.
 *
 * For explanation of why you'd want to perform rounding operations on a String
 * rather than a Number, see http://stackoverflow.com/a/38676273/1709587
 *
 * @param {(number|string)} num
 * @param {number} dp
 * @return {string}
 */
function roundStringNumberWithoutTrailingZeroes (num, dp) {
    if (arguments.length != 2) throw new Error("2 arguments required");

    num = String(num);
    if (num.indexOf('e+') != -1) {
        // Can't round numbers this large because their string representation
        // contains an exponent, like 9.99e+37
        throw new Error("num too large");
    }
    if (num.indexOf('.') == -1) {
        // Nothing to do
        return num;
    }

    var parts = num.split('.'),
        beforePoint = parts[0],
        afterPoint = parts[1],
        shouldRoundUp = afterPoint[dp] >= 5,
        finalNumber;

    afterPoint = afterPoint.slice(0, dp);
    if (!shouldRoundUp) {
        finalNumber = beforePoint + '.' + afterPoint;
    } else if (/^9+$/.test(afterPoint)) {
        // If we need to round up a number like 1.9999, increment the integer
        // before the decimal point and discard the fractional part.
        finalNumber = Number(beforePoint)+1;
    } else {
        // Starting from the last digit, increment digits until we find one
        // that is not 9, then stop
        var i = dp-1;
        while (true) {
            if (afterPoint[i] == '9') {
                afterPoint = afterPoint.substr(0, i) +
                             '0' +
                             afterPoint.substr(i+1);
                i--;
            } else {
                afterPoint = afterPoint.substr(0, i) +
                             (Number(afterPoint[i]) + 1) +
                             afterPoint.substr(i+1);
                break;
            }
        }

        finalNumber = beforePoint + '.' + afterPoint;
    }

    // Remove trailing zeroes from fractional part before returning
    return finalNumber.replace(/0+$/, '')
}

Example usage:

> roundStringNumberWithoutTrailingZeroes(1.6, 2)
'1.6'
> roundStringNumberWithoutTrailingZeroes(10000, 2)
'10000'
> roundStringNumberWithoutTrailingZeroes(0.015, 2)
'0.02'
> roundStringNumberWithoutTrailingZeroes('0.015000', 2)
'0.02'
> roundStringNumberWithoutTrailingZeroes(1, 1)
'1'
> roundStringNumberWithoutTrailingZeroes('0.015', 2)
'0.02'
> roundStringNumberWithoutTrailingZeroes(0.01499999999999999944488848768742172978818416595458984375, 2)
'0.02'
> roundStringNumberWithoutTrailingZeroes('0.01499999999999999944488848768742172978818416595458984375', 2)
'0.01'

The function above is probably what you want to use to avoid users ever witnessing numbers that they have entered being rounded wrongly.

(As an alternative, you could also try the round10 library which provides a similarly-behaving function with a wildly different implementation.)

But what if you have the second kind of Number - a value taken from a continuous scale, where there's no reason to think that approximate decimal representations with fewer decimal places are more accurate than those with more? In that case, we don't want to respect the String representation, because that representation (as explained in the spec) is already sort-of-rounded; we don't want to make the mistake of saying "0.014999999...375 rounds up to 0.015, which rounds up to 0.02, so 0.014999999...375 rounds up to 0.02".

Here we can simply use the built-in toFixed method. Note that by calling Number() on the String returned by toFixed, we get a Number whose String representation has no trailing zeroes (thanks to the way JavaScript computes the String representation of a Number, discussed earlier in this answer).

/**
 * Takes a float and rounds it to at most dp decimal places. For example
 *
 *     roundFloatNumberWithoutTrailingZeroes(1.2345, 3)
 *
 * returns 1.234
 *
 * Note that since this treats the value passed to it as a floating point
 * number, it will have counterintuitive results in some cases. For instance,
 * 
 *     roundFloatNumberWithoutTrailingZeroes(0.015, 2)
 *
 * gives 0.01 where 0.02 might be expected. For an explanation of why, see
 * http://stackoverflow.com/a/38676273/1709587. You may want to consider using the
 * roundStringNumberWithoutTrailingZeroes function there instead.
 *
 * @param {number} num
 * @param {number} dp
 * @return {number}
 */
function roundFloatNumberWithoutTrailingZeroes (num, dp) {
    var numToFixedDp = Number(num).toFixed(dp);
    return Number(numToFixedDp);
}

number=(parseInt((number +0.005)*100))/100;     

add 0.005 if you want to normal round (2 decimals)

8.123 +0.005=> 8.128*100=>812/100=>8.12   

8.126 +0.005=> 8.131*100=>813/100=>8.13   

Since ES6 there is a 'proper' way (without overriding statics and creating workarounds) to do this by using toPrecision

_x000D_
_x000D_
var x = 1.49999999999;_x000D_
console.log(x.toPrecision(4));_x000D_
console.log(x.toPrecision(3));_x000D_
console.log(x.toPrecision(2));_x000D_
_x000D_
var y = Math.PI;_x000D_
console.log(y.toPrecision(6));_x000D_
console.log(y.toPrecision(5));_x000D_
console.log(y.toPrecision(4));_x000D_
_x000D_
var z = 222.987654_x000D_
console.log(z.toPrecision(6));_x000D_
console.log(z.toPrecision(5));_x000D_
console.log(z.toPrecision(4));
_x000D_
_x000D_
_x000D_

then you can just parseFloat and zeroes will 'go away'.

_x000D_
_x000D_
console.log(parseFloat((1.4999).toPrecision(3)));_x000D_
console.log(parseFloat((1.005).toPrecision(3)));_x000D_
console.log(parseFloat((1.0051).toPrecision(3)));
_x000D_
_x000D_
_x000D_

It doesn't solve the '1.005 rounding problem' though - since it is intrinsic to how float fractions are being processed.

_x000D_
_x000D_
console.log(1.005 - 0.005);
_x000D_
_x000D_
_x000D_

If you are open to libraries you can use bignumber.js

_x000D_
_x000D_
console.log(1.005 - 0.005);_x000D_
console.log(new BigNumber(1.005).minus(0.005));_x000D_
_x000D_
console.log(new BigNumber(1.005).round(4));_x000D_
console.log(new BigNumber(1.005).round(3));_x000D_
console.log(new BigNumber(1.005).round(2));_x000D_
console.log(new BigNumber(1.005).round(1));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bignumber.js/2.3.0/bignumber.min.js"></script>
_x000D_
_x000D_
_x000D_


Slight modification of this answer that seems to work well.

Function

function roundToStep(value, stepParam) {
   var step = stepParam || 1.0;
   var inv = 1.0 / step;
   return Math.round(value * inv) / inv;
}

Usage

roundToStep(2.55) = 3
roundToStep(2.55, 0.1) = 2.6
roundToStep(2.55, 0.01) = 2.55

A simple general rounding function could be following:

Steps are:

  1. Multiply the number by (10 to the power of number of decimal place) using Math.pow(10,places).
  2. Round the result to whole integer using Math.Round.
  3. Divide the result back by (10 to the power of number of decimal place) Math.pow(10,places).

Example:

number is: 1.2375 to be rounded to 3 decimal places

  1. 1.2375 * (10^3) ==> 1.2375 * 1000 = 1237.5
  2. Round to integer ==> 1238
  3. Divide 1238 by (10^3) ==> 1238 / 1000 = 1.238

(note: 10^3 means Math.pow(10,3)).

_x000D_
_x000D_
 function numberRoundDecimal(v,n) {_x000D_
 return Math.round((v+Number.EPSILON)*Math.pow(10,n))/Math.pow(10,n)}_x000D_
_x000D_
_x000D_
// ------- tests --------_x000D_
console.log(numberRoundDecimal(-0.024641163062896567,3))  // -0.025_x000D_
console.log(numberRoundDecimal(0.9993360575508052,3))     // 0.999_x000D_
console.log(numberRoundDecimal(1.0020739645577939,3))     // 1.002_x000D_
console.log(numberRoundDecimal(0.975,0))                  // 1_x000D_
console.log(numberRoundDecimal(0.975,1))                  // 1_x000D_
console.log(numberRoundDecimal(0.975,2))                  // 0.98_x000D_
console.log(numberRoundDecimal(1.005,2))                  // 1.01
_x000D_
_x000D_
_x000D_


If the value is a text type:

parseFloat("123.456").toFixed(2);

If the value is a number:

var numb = 123.23454;
numb = numb.toFixed(2);

There is a downside that values like 1.5 will give "1.50" as the output. A fix suggested by @minitech:

var numb = 1.5;
numb = +numb.toFixed(2);
// Note the plus sign that drops any "extra" zeroes at the end.
// It changes the result (which is a string) into a number again (think "0 + foo"),
// which means that it uses only as many digits as necessary.

It seems like Math.round is a better solution. But it is not! In some cases it will NOT round correctly:

Math.round(1.005 * 1000)/1000 // Returns 1 instead of expected 1.01!

toFixed() will also NOT round correctly in some cases (tested in Chrome v.55.0.2883.87)!

Examples:

parseFloat("1.555").toFixed(2); // Returns 1.55 instead of 1.56.
parseFloat("1.5550").toFixed(2); // Returns 1.55 instead of 1.56.
// However, it will return correct result if you round 1.5551.
parseFloat("1.5551").toFixed(2); // Returns 1.56 as expected.

1.3555.toFixed(3) // Returns 1.355 instead of expected 1.356.
// However, it will return correct result if you round 1.35551.
1.35551.toFixed(2); // Returns 1.36 as expected.

I guess, this is because 1.555 is actually something like float 1.55499994 behind the scenes.

Solution 1 is to use a script with required rounding algorithm, for example:

function roundNumber(num, scale) {
  if(!("" + num).includes("e")) {
    return +(Math.round(num + "e+" + scale)  + "e-" + scale);
  } else {
    var arr = ("" + num).split("e");
    var sig = ""
    if(+arr[1] + scale > 0) {
      sig = "+";
    }
    return +(Math.round(+arr[0] + "e" + sig + (+arr[1] + scale)) + "e-" + scale);
  }
}

https://plnkr.co/edit/uau8BlS1cqbvWPCHJeOy?p=preview

NOTE: This is not a universal solution for everyone. There are several different rounding algorithms, your implementation can be different, depends on your requirements. https://en.wikipedia.org/wiki/Rounding

Solution 2 is to avoid front end calculations and pull rounded values from the backend server.

Edit: Another possible solution, which is not a bullet proof also.

Math.round((num + Number.EPSILON) * 100) / 100

In some cases, when you round number like 1.3549999999999998 it will return incorrect result. Should be 1.35 but result is 1.36.


+(10).toFixed(2); // = 10
+(10.12345).toFixed(2); // = 10.12

(10).toFixed(2); // = 10.00
(10.12345).toFixed(2); // = 10.12

There is a solution working for all numbers, give it a try. expression is given below.

Math.round((num + 0.00001) * 100) / 100. Try Math.round((1.005 + 0.00001) * 100) / 100 and Math.round((1.0049 + 0.00001) * 100) / 100

I recently tested every possible solution and finally arrived at the output after trying almost 10 times. Here is a screenshot of issue arised during caculations, Screen Capture.

head over to the amount field, It's returning almost infinite. I gave a try to toFixed() method but it's not working for some cases(i.e try with PI) and finally derived s solution given above.


Use this function Number(x).toFixed(2);


One way to achieve such a rounding only if necessary is to use Number.prototype.toLocaleString():

myNumber.toLocaleString('en', {maximumFractionDigits:2, useGrouping:false})

This will provide exactly the output you expect, but as strings. You can still convert those back to numbers if that's not the data type you expect.


Here's my solution to this problem:

function roundNumber(number, precision = 0) {
var num = number.toString().replace(",", "");
var integer, decimal, significantDigit;

if (num.indexOf(".") > 0 && num.substring(num.indexOf(".") + 1).length > precision && precision > 0) {
    integer = parseInt(num).toString();
    decimal = num.substring(num.indexOf(".") + 1);
    significantDigit = Number(decimal.substr(precision, 1));

    if (significantDigit >= 5) {
        decimal = (Number(decimal.substr(0, precision)) + 1).toString();
        return integer + "." + decimal;
    } else {
        decimal = (Number(decimal.substr(0, precision)) + 1).toString();
        return integer + "." + decimal;
    }
}
else if (num.indexOf(".") > 0) {
    integer = parseInt(num).toString();
    decimal = num.substring(num.indexOf(".") + 1);
    significantDigit = num.substring(num.length - 1, 1);

    if (significantDigit >= 5) {
        decimal = (Number(decimal) + 1).toString();
        return integer + "." + decimal;
    } else {            
        return integer + "." + decimal;
    }
} 

return number;
}

For me Math.round() was not giving correct answer. I found toFixed(2) works better. Below are examples of both:

_x000D_
_x000D_
console.log(Math.round(43000 / 80000) * 100); // wrong answer_x000D_
_x000D_
console.log(((43000 / 80000) * 100).toFixed(2)); // correct answer
_x000D_
_x000D_
_x000D_


You can use

function roundToTwo(num) {    
    return +(Math.round(num + "e+2")  + "e-2");
}

I found this over on MDN. Their way avoids the problem with 1.005 that was mentioned.

roundToTwo(1.005)
1.01
roundToTwo(10)
10
roundToTwo(1.7777777)
1.78
roundToTwo(9.1)
9.1
roundToTwo(1234.5678)
1234.57

Here is a prototype method:

Number.prototype.round = function(places){
    places = Math.pow(10, places); 
    return Math.round(this * places)/places;
}

var yournum = 10.55555;
yournum = yournum.round(2);

If you happen to already be using the d3 library, they have a powerful number formatting library: https://github.com/mbostock/d3/wiki/Formatting

Rounding specifically is here: https://github.com/mbostock/d3/wiki/Formatting#d3_round

In your case, the answer is:

> d3.round(1.777777, 2)
1.78
> d3.round(1.7, 2)
1.7
> d3.round(1, 2)
1

I still don't think anyone gave him the answer to how to only do the rounding if needed. The easiest way I see to do it is to check if there is even a decimal in the number, like so:

var num = 3.21;
if ( (num+"").indexOf('.') >= 0 ) { //at least assert to string first...
    // whatever code you decide to use to round
}

I know there are many answers, but most of them have side effect in some specific cases.

Easiest and shortest solution without any side effects is following:

Number((2.3456789).toFixed(2)) // 2.35

It rounds properly and returns number instead of string

console.log(Number((2.345).toFixed(2)))  // 2.35
console.log(Number((2.344).toFixed(2)))  // 2.34
console.log(Number((2).toFixed(2)))      // 2
console.log(Number((-2).toFixed(2)))     // -2
console.log(Number((-2.345).toFixed(2))) // -2.35

console.log(Number((2.345678).toFixed(3))) // 2.346

2017
Just use native code .toFixed()

number = 1.2345;
number.toFixed(2) // "1.23"

If you need to be strict and add digits just if needed it can use replace

number = 1; // "1"
number.toFixed(5).replace(/\.?0*$/g,'');

parseFloat("1.555").toFixed(2); // Returns 1.55 instead of 1.56.

1.55 is the absolute correct result, because there exists no exact representation of 1.555 in the computer. If reading 1.555 it is rounded to the nearest possible value = 1.55499999999999994 (64 bit float). And rounding this number by toFixed(2) results in 1.55.

All other functions provided here give fault result, if the input is 1.55499999999999.

Solution: Append the digit "5" before scanning to rounding up (more exact: rounding away from 0) the number. Do this only, if the number is really a float (has a decimal point).

parseFloat("1.555"+"5").toFixed(2); // Returns 1.56

The rounding problem can be avoided by using numbers represented in exponential notation.

public roundFinancial(amount: number, decimals: number) {
    return Number(Math.round(Number(`${amount}e${decimals}`)) + `e-${decimals}`);
}

I just wanted to share my approach, based on previously mentioned answers:

Let's create a function that rounds any given numeric value to a given amount of decimal places:

function roundWDecimals(n, decimals) {
    if (!isNaN(parseFloat(n)) && isFinite(n)) {
        if (typeof(decimals) == typeof(undefined)) {
            decimals = 0;
        }
        var decimalPower = Math.pow(10, decimals);
        return Math.round(parseFloat(n) * decimalPower) / decimalPower;
    }
    return NaN;
}

And introduce a new "round" method for numbers prototype:

Object.defineProperty(Number.prototype, 'round', {
    enumerable: false,
    value: function(decimals) {
        return roundWDecimals(this, decimals);
    }
});

And you can test it:

_x000D_
_x000D_
function roundWDecimals(n, decimals) {_x000D_
    if (!isNaN(parseFloat(n)) && isFinite(n)) {_x000D_
        if (typeof(decimals) == typeof(undefined)) {_x000D_
            decimals = 0;_x000D_
        }_x000D_
        var decimalPower = Math.pow(10, decimals);_x000D_
        return Math.round(parseFloat(n) * decimalPower) / decimalPower;_x000D_
    }_x000D_
    return NaN;_x000D_
}_x000D_
Object.defineProperty(Number.prototype, 'round', {_x000D_
    enumerable: false,_x000D_
    value: function(decimals) {_x000D_
        return roundWDecimals(this, decimals);_x000D_
    }_x000D_
});_x000D_
_x000D_
var roundables = [_x000D_
    {num: 10, decimals: 2},_x000D_
    {num: 1.7777777, decimals: 2},_x000D_
    {num: 9.1, decimals: 2},_x000D_
    {num: 55.55, decimals: 1},_x000D_
    {num: 55.549, decimals: 1},_x000D_
    {num: 55, decimals: 0},_x000D_
    {num: 54.9, decimals: 0},_x000D_
    {num: -55.55, decimals: 1},_x000D_
    {num: -55.551, decimals: 1},_x000D_
    {num: -55, decimals: 0},_x000D_
    {num: 1.005, decimals: 2},_x000D_
    {num: 1.005, decimals: 2},_x000D_
    {num: 19.8000000007, decimals: 2},_x000D_
  ],_x000D_
  table = '<table border="1"><tr><th>Num</th><th>Decimals</th><th>Result</th></tr>';_x000D_
$.each(roundables, function() {_x000D_
  table +=_x000D_
    '<tr>'+_x000D_
      '<td>'+this.num+'</td>'+_x000D_
      '<td>'+this.decimals+'</td>'+_x000D_
      '<td>'+this.num.round(this.decimals)+'</td>'+_x000D_
    '</tr>'_x000D_
  ;_x000D_
});_x000D_
table += '</table>';_x000D_
$('.results').append(table);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="results"></div>
_x000D_
_x000D_
_x000D_


MarkG and Lavamantis offered a much better solution than the one that has been accepted. It's a shame they don't get more upvotes!

Here is the function I use to solve the floating point decimals issues also based on MDN. It is even more generic (but less concise) than Lavamantis's solution:

function round(value, exp) {
  if (typeof exp === 'undefined' || +exp === 0)
    return Math.round(value);

  value = +value;
  exp  = +exp;

  if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0))
    return NaN;

  // Shift
  value = value.toString().split('e');
  value = Math.round(+(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)));

  // Shift back
  value = value.toString().split('e');
  return +(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp));
}

Use it with:

round(10.8034, 2);      // Returns 10.8
round(1.275, 2);        // Returns 1.28
round(1.27499, 2);      // Returns 1.27
round(1.2345678e+2, 2); // Returns 123.46

Compared to Lavamantis's solution, we can do...

round(1234.5678, -2); // Returns 1200
round("123.45");      // Returns 123

You could also override the Math.round function to do the rounding correct and add a parameter for decimals and use it like: Math.round(Number, Decimals). Keep in mind that this overrides the built in component Math.round and giving it another property then it original is.

var round = Math.round;
Math.round = function (value, decimals) {
  decimals = decimals || 0;
  return Number(round(value + 'e' + decimals) + 'e-' + decimals);
}

Then you can simply use it like this:

Math.round(1.005, 2);

https://jsfiddle.net/k5tpq3pd/3/


the proposed answers while generally correct doesn't consider the precision of the passed in number, which is not expressed as requirement in the original question, but may be a requirement in case of scientific application where 3 is different from 3.00 (for example) as the number of decimal digits represents the precision of the instrument that have acquired the value or the accuracy of a calculation. In fact the proposed answers rounds 3.001 to 3 while by keeping the information about the precision of the number should be 3.00

below a function that takes in account that

_x000D_
_x000D_
function roundTo(value, decimal) {_x000D_
_x000D_
    let absValue = Math.abs(value);_x000D_
    let int = Math.floor(absValue).toString().length;_x000D_
    let dec = absValue.toString().length - int;_x000D_
    dec -= (Number.isInteger(absValue) ? 0 : 1);_x000D_
    return value.toPrecision(int + Math.min(dec, decimal));_x000D_
  _x000D_
}
_x000D_
_x000D_
_x000D_


It may work for you,

Math.round(num * 100)/100;

to know the difference between toFixed and round. You can have a look at Math.round(num) vs num.toFixed(0) and browser inconsistencies.


FINAL UPDATE:

Leaving this answer here for posterity, but I would recommend using @AmrAli's adaptation of the DecimalPrecision function, as it is equipped to handle exponential notation as well. I had originally sought to avoid any string conversion/manipulation of any kind for performance reasons, but there is virtually no difference in performance with his implementation.

EDIT 8/22/2020: I think it should be clarified here that the goal of these efforts is not to completely eliminate the inherent rounding errors caused by the floating point data type, as that will never be possible without switching to a data type that is actually storing the value as a base10 (decimal). The goal really should be to push the inaccuracies as far out to the edge as possible, so that you can perform mathematical operations on a given value without producing the bug. The moment your value hits the absolute edge, where simply invoking the value would cause JS to produce the bug, either before or after you've manipulated it, there's nothing more you could do to alleviate that. For example, if you instantiate the value 0.014999999999999999, JS will immediately round it to 0.015. Therefore if you passed that value to any of these functions, you are actually passing 0.015. At that point you couldn't even convert to string first and then manipulate it, the value would have to be instantiated as a string from the start for that to work. The goal, and only reasonable expectation, of any functions created to alleviate this bug is simply to allow for mathematical operations to be performed on floating point values while pushing the bug all the way out to the edge where either the starting value, or resulting value would produce the bug simply by being invoked anyway. The only other alternative solutions would be to store the whole numbers and decimal values independently, both as integers, so that they are only ever invoked as such, or to always store the value as a string and use a combination of string manipulation and integer based math to perform operations on it.

After running through various iterations of all the possible ways to achieve true accurate decimal rounding precision, it is clear that the most accurate and efficient solution is to use Number.EPSILON. This provides a true mathematical solution to the problem of floating point math precision. It can be easily polyfilled as shown here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/EPSILON to support all of the last remaining IE users (then again maybe we should stop doing that).

Adapted from the solution provided here: https://stackoverflow.com/a/48850944/6910392

A simple drop in solution that provides accurate decimal rounding, flooring, and ceiling, with an optional precision variable without adding a whole library.

05-19-2020 UPDATE: As Sergey noted in the comments, there is a limitation to this (or any) method that's worth pointing out. In the case of numbers like 0.014999999999999999, you will still experience inaccuracies which are the result of hitting the absolute edge of accuracy limitations for floating point value storage. There is no math or other solution that can be applied to account for that, as the value itself is immediately evaluated as 0.015. You can confirm this by simply invoking that value by itself in the console. Due to this limitation, it would not even be possible to use string manipulation to reduce this value, as its string representation is simply "0.015". Any solution to account for this would need to be applied logically at the source of the data before ever accepting the value into a script, eg restricting the character length of a field etc. That would be a consideration that would need to be taken into account on a case by case basis to determine the best approach.

08-19-2020 UPDATE: Per Amr's comment, the ceil and floor functions will produce undesired results when the input value is an integer. This is due to the addition applied to the input with Number.EPSILON in order to offset the expected float inaccuracy. The function has been updated to check if the input value is an integer and return the value unchanged, as that is the correct result of either function when applied to a whole number.

*Note: This issue also reveals that while the ceil and floor functions still require the application of the Number.EPSILON adjustment, they do produce undesirable results when applied to a value where the number of decimals in the input number is lower than the number of decimals requested for the output (p). For example, ceil(17.1, 5) should return 17.1 in relation to expected "ceil" function behavior when applied to whole numbers in mathematics, where all decimal places after "1" are assumed to be 0. To correct for this, I've added an additional function check to identify if the number of decimals in the input number is lower than the requested output decimals, and return the number unchanged, just as with whole numbers.

_x000D_
_x000D_
var DecimalPrecision = (function(){
        if (Number.EPSILON === undefined) {
            Number.EPSILON = Math.pow(2, -52);
        }
        if(Number.isInteger === undefined){
            Number.isInteger = function(value) {
                return typeof value === 'number' && 
                isFinite(value) && 
                Math.floor(value) === value;
            };
        }
        this.isRound = function(n,p){
            let l = n.toString().split('.')[1].length;
            return (p >= l);
        }
        this.round = function(n, p=2){
            if(Number.isInteger(n) || this.isRound(n,p))
                return n;
            let r = 0.5 * Number.EPSILON * n;
            let o = 1; while(p-- > 0) o *= 10;
            if(n<0)
                o *= -1;
            return Math.round((n + r) * o) / o;
        }
        this.ceil = function(n, p=2){
            if(Number.isInteger(n) || this.isRound(n,p))
                return n;
            let r = 0.5 * Number.EPSILON * n;
            let o = 1; while(p-- > 0) o *= 10;
            
            return Math.ceil((n + r) * o) / o;
        }
        this.floor = function(n, p=2){
            if(Number.isInteger(n) || this.isRound(n,p))
                return n;
            let r = 0.5 * Number.EPSILON * n;
            let o = 1; while(p-- > 0) o *= 10;
            
            return Math.floor((n + r) * o) / o;
        }
        return this;
    })();
    console.log(DecimalPrecision.round(1.005));
    console.log(DecimalPrecision.ceil(1.005));
    console.log(DecimalPrecision.floor(1.005));
    console.log(DecimalPrecision.round(1.0049999));
    console.log(DecimalPrecision.ceil(1.0049999));
    console.log(DecimalPrecision.floor(1.0049999));
    console.log(DecimalPrecision.round(2.175495134384,7));
    console.log(DecimalPrecision.round(2.1753543549,8));
    console.log(DecimalPrecision.round(2.1755465135353,4));
    console.log(DecimalPrecision.ceil(17,4));
    console.log(DecimalPrecision.ceil(17.1,4));
    console.log(DecimalPrecision.ceil(17.1,15));
_x000D_
_x000D_
_x000D_


I've read all the answers, the answers of similar questions and the complexity of the most "good" solutions didn't satisfy me. I don't want to put a huge round function set, or a small one but fails on scientific notation. So, I came up with this function. It may help someone in my situation:

function round(num, dec) {
   const [sv, ev] = num.toString().split('e');
   return Number(Number(Math.round(parseFloat(sv + 'e' + dec)) + 'e-' + dec) + 'e' + (ev || 0));
}

I didn't run any performance test because I will call this just to update the UI of my application. The function gives the following results for a quick test:

// 1/3563143 = 2.806510993243886e-7
round(1/3563143, 2)  // returns `2.81e-7`

round(1.31645, 4)    // returns 1.3165

round(-17.3954, 2)   // returns -17.4

This is enough for me.


I wrote the following set of functions for myself. Maybe it will help you too.

function float_exponent(number) {
    exponent = 1;
    while (number < 1.0) {
        exponent += 1
        number *= 10
    }
    return exponent;
}
function format_float(number, extra_precision) {
    precision = float_exponent(number) + (extra_precision || 0)
    return number.toFixed(precision).split(/\.?0+$/)[0]
}

Usage:

format_float(1.01); // 1
format_float(1.06); // 1.1
format_float(0.126); // 0.13
format_float(0.000189); // 0.00019

For you case:

format_float(10, 1); // 10
format_float(9.1, 1); // 9.1
format_float(1.77777, 1); // 1.78

The big challenge on this seemingly simple task is that we want it to yield psychologically expected results even if the input contains minimal rounding errors to start with (not mentioning the errors which will happen within our calculation). If we know that the real result is exactly 1.005, we expect that rounding to two digits yields 1.01, even if the 1.005 is the result of a large computation with loads of rounding errors on the way.

The problem becomes even more obvious when dealing with floor() instead of round(). For example, when cutting everything away after the last two digits behind the dot of 33.3, we would certainly not expect to get 33.29 as a result, but that is what happens:

_x000D_
_x000D_
console.log(Math.floor(33.3 * 100) / 100)
_x000D_
_x000D_
_x000D_

In simple cases, the solution is to perform calculation on strings instead of floating point numbers, and thus avoid rounding errors completely. However, this option fails at the first non-trivial mathematical operation (including most divsions), and it is slow.

When operating on floating point numbers, the solution is to introduce a parameter which names the amount by which we are willing to deviate from the actual computation result, in order to output the psychologically expected result.

_x000D_
_x000D_
var round = function(num, digits = 2, compensateErrors = 2) {_x000D_
  if (num < 0) {_x000D_
    return -this.round(-num, digits, compensateErrors);_x000D_
  }_x000D_
  const pow = Math.pow(10, digits);_x000D_
  return (Math.round(num * pow * (1 + compensateErrors * Number.EPSILON)) / pow);_x000D_
}_x000D_
_x000D_
/* --- testing --- */_x000D_
_x000D_
console.log("Edge cases mentioned in this thread:")_x000D_
var values = [ 0.015, 1.005, 5.555, 156893.145, 362.42499999999995, 1.275, 1.27499, 1.2345678e+2, 2.175, 5.015, 58.9 * 0.15 ];_x000D_
values.forEach((n) => {_x000D_
  console.log(n + " -> " + round(n));_x000D_
  console.log(-n + " -> " + round(-n));_x000D_
});_x000D_
_x000D_
console.log("\nFor numbers which are so large that rounding cannot be performed anyway within computation precision, only string-based computation can help.")_x000D_
console.log("Standard: " + round(1e+19));_x000D_
console.log("Compensation = 1: " + round(1e+19, 2, 1));_x000D_
console.log("Effectively no compensation: " + round(1e+19, 2, 0.4));
_x000D_
_x000D_
_x000D_

Note: Internet Explorer does not know Number.EPSILON. If you are in the unhappy position of still having to support it, you can use a shim, or just define the constant yourself for that specific browser family.


This did the trick for me (TypeScript):

round(decimal: number, decimalPoints: number): number{
    let roundedValue = Math.round(decimal * Math.pow(10, decimalPoints)) / Math.pow(10, decimalPoints);

    console.log(`Rounded ${decimal} to ${roundedValue}`);
    return roundedValue;
}

// Sample output:
Rounded 18.339840000000436 to 18.34
Rounded 52.48283999999984 to 52.48
Rounded 57.24612000000036 to 57.25
Rounded 23.068320000000142 to 23.07
Rounded 7.792980000000398 to 7.79
Rounded 31.54157999999981 to 31.54
Rounded 36.79686000000004 to 36.8
Rounded 34.723080000000124 to 34.72
Rounded 8.4375 to 8.44
Rounded 15.666960000000074 to 15.67
Rounded 29.531279999999924 to 29.53
Rounded 8.277420000000006 to 8.28

Here is the shortest and complete answer:

function round(num, decimals) {
        var n = Math.pow(10, decimals);
        return Math.round( (n * num).toFixed(decimals) )  / n;
};

This also takes care of the example case 1.005 which will return 1.01.


This function works for me. You just pass in the number and the places you want to round and it does what it needs to do easily.

round(source,n) {
 let places = Math.pow(10,n);

 return Math.round(source * places) / places;
}

If you are using lodash library, you can use the round method of lodash like following.

_.round(number, precision)

Eg:

_.round(1.7777777, 2) = 1.78

Based on the choosen answer and the upvoted comment on the same question:

Math.round((num + 0.00001) * 100) / 100

This works for both these examples:

Math.round((1.005 + 0.00001) * 100) / 100

Math.round((1.0049 + 0.00001) * 100) / 100

The easiest approach would be to use toFixed and then strip trailing zeros using the Number function:

const number = 15.5;
Number(number.toFixed(2)); // 15.5
const number = 1.7777777;
Number(number.toFixed(2)); // 1.78

Easiest way:

+num.toFixed(2)

It converts it to a string, and then back into an integer / float.


None of the answers found here is correct. @stinkycheeseman asked to round up, you all rounded the number.

To round up, use this:

Math.ceil(num * 100)/100;

Just for the record, the scaling method could theoretically return Infinity if the number and the digits you want to round to are big enough. In JavaScript that shouldn't be a problem since the maximum number is 1.7976931348623157e+308, but if you're working with really big numbers or a lot of decimal places you could try this function instead:

_x000D_
_x000D_
Number.prototype.roundTo = function(digits)_x000D_
{_x000D_
    var str = this.toString();_x000D_
    var split = this.toString().split('e');_x000D_
    var scientific = split.length > 1;_x000D_
    var index;_x000D_
    if (scientific)_x000D_
    {_x000D_
        str = split[0];_x000D_
        var decimal = str.split('.');_x000D_
        if (decimal.length < 2)_x000D_
            return this;_x000D_
        index = decimal[0].length + 1 + digits;_x000D_
    }_x000D_
    else_x000D_
        index = Math.floor(this).toString().length + 1 + digits;_x000D_
    if (str.length <= index)_x000D_
        return this;_x000D_
    var digit = str[index + 1];_x000D_
    var num = Number.parseFloat(str.substring(0, index));_x000D_
    if (digit >= 5)_x000D_
    {_x000D_
        var extra = Math.pow(10, -digits);_x000D_
        return this < 0 ? num - extra : num + extra;_x000D_
    }_x000D_
    if (scientific)_x000D_
        num += "e" + split[1];_x000D_
    return num;_x000D_
}
_x000D_
_x000D_
_x000D_


From the existing answers I found another solution which seems to work great, which also works with sending in a string and eliminates trailing zeros.

function roundToDecimal(string, decimals) {
    return parseFloat(parseFloat(string).toFixed(decimals));
}

It doesn't take in to account if you send in some bull.. like "apa" though. Or it will probably throw an error which I think is the proper way anyway, it's never good to hide errors that should be fixed (by the calling function).


MarkG's answer is the correct one. Here's a generic extension for any number of decimal places.

Number.prototype.round = function(places) {
  return +(Math.round(this + "e+" + places)  + "e-" + places);
}

Usage:

var n = 1.7777;    
n.round(2); // 1.78

Unit test:

it.only('should round floats to 2 places', function() {

  var cases = [
    { n: 10,      e: 10,    p:2 },
    { n: 1.7777,  e: 1.78,  p:2 },
    { n: 1.005,   e: 1.01,  p:2 },
    { n: 1.005,   e: 1,     p:0 },
    { n: 1.77777, e: 1.8,   p:1 }
  ]

  cases.forEach(function(testCase) {
    var r = testCase.n.round(testCase.p);
    assert.equal(r, testCase.e, 'didn\'t get right number');
  });
})

A different approach is to use a library. Why not lodash:

const _ = require("lodash")
const roundedNumber = _.round(originalNumber, 2)

Try this light weight solution:

function round(x, digits){
  return parseFloat(x.toFixed(digits))
}

 round(1.222,  2) ;
 // 1.22
 round(1.222, 10) ;
 // 1.222

To not deal with many 0s, use this variant:

Math.round(num * 1e2) / 1e2

Quick helper function where rounging is You default rounding: let rounding=4;

let round=(number)=>{ let multiply=Math.pow(10,rounding);  return Math.round(number*multiply)/multiply};

console.log(round(0.040579431));

=> 0.0406


In the node environment I just use the roundTo module:

const roundTo = require('round-to');
...
roundTo(123.4567, 2);

// 123.46

Use something like this "parseFloat(parseFloat(value).toFixed(2))"

parseFloat(parseFloat("1.7777777").toFixed(2))-->1.78 
parseFloat(parseFloat("10").toFixed(2))-->10 
parseFloat(parseFloat("9.1").toFixed(2))-->9.1

A precise rounding method. Source: Mozilla

(function(){

    /**
     * Decimal adjustment of a number.
     *
     * @param   {String}    type    The type of adjustment.
     * @param   {Number}    value   The number.
     * @param   {Integer}   exp     The exponent (the 10 logarithm of the adjustment base).
     * @returns {Number}            The adjusted value.
     */
    function decimalAdjust(type, value, exp) {
        // If the exp is undefined or zero...
        if (typeof exp === 'undefined' || +exp === 0) {
            return Math[type](value);
        }
        value = +value;
        exp = +exp;
        // If the value is not a number or the exp is not an integer...
        if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
            return NaN;
        }
        // Shift
        value = value.toString().split('e');
        value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
        // Shift back
        value = value.toString().split('e');
        return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
    }

    // Decimal round
    if (!Math.round10) {
        Math.round10 = function(value, exp) {
            return decimalAdjust('round', value, exp);
        };
    }
    // Decimal floor
    if (!Math.floor10) {
        Math.floor10 = function(value, exp) {
            return decimalAdjust('floor', value, exp);
        };
    }
    // Decimal ceil
    if (!Math.ceil10) {
        Math.ceil10 = function(value, exp) {
            return decimalAdjust('ceil', value, exp);
        };
    }
})();

Examples:

// Round
Math.round10(55.55, -1); // 55.6
Math.round10(55.549, -1); // 55.5
Math.round10(55, 1); // 60
Math.round10(54.9, 1); // 50
Math.round10(-55.55, -1); // -55.5
Math.round10(-55.551, -1); // -55.6
Math.round10(-55, 1); // -50
Math.round10(-55.1, 1); // -60
Math.round10(1.005, -2); // 1.01 -- compare this with Math.round(1.005*100)/100 above
// Floor
Math.floor10(55.59, -1); // 55.5
Math.floor10(59, 1); // 50
Math.floor10(-55.51, -1); // -55.6
Math.floor10(-51, 1); // -60
// Ceil
Math.ceil10(55.51, -1); // 55.6
Math.ceil10(51, 1); // 60
Math.ceil10(-55.59, -1); // -55.5
Math.ceil10(-59, 1); // -50

Using Brian Ustas's solution:

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

Please use the below function if you don't want to round off.

function ConvertToDecimal(num) {
  num = num.toString(); // If it's not already a String
  num = num.slice(0, (num.indexOf(".")) + 3); // With 3 exposing the hundredths place    
alert('M : ' + Number(num)); // If you need it back as a Number     
}

Starting from the example proposed over the precisionRound that I found on MDN (that event for 1.005 returs 1 and not 1.01), I write a custom precisionRound that manage a random precision number and for 1.005 returns 1.01.

This is the function:

function precisionRound(number, precision)
{
  if(precision < 0)
  {
    var factor = Math.pow(10, precision);
    return Math.round(number * factor) / factor;
  }
  else
    return +(Math.round(number + "e+"+precision)  + "e-"+precision);
}

console.log(precisionRound(1234.5678, 1));  // output: 1234.6
console.log(precisionRound(1234.5678, -1)); // output: 1230
console.log(precisionRound(1.005, 2));      // output: 1.01
console.log(precisionRound(1.0005, 2));     // output: 1
console.log(precisionRound(1.0005, 3));     // output: 1.001
console.log(precisionRound(1.0005, 4));     // output: 1.0005

For TypeScript:

public static precisionRound(number: number, precision: number)
{
  if (precision < 0)
  {
    let factor = Math.pow(10, precision);
    return Math.round(number * factor) / factor;
  }
  else
    return +(Math.round(Number(number + "e+" + precision)) +
      "e-" + precision);
}

A slight variation on this is if you need to format a currency amount as either being a whole amount of currency or an amount with fractional currency parts.

For example:

1 should output $1

1.1 should output $1.10

1.01 should output $1.01

Assuming amount is a number:

const formatAmount = (amount) => amount % 1 === 0 ? amount : amount.toFixed(2);

If amount is not a number then use parseFloat(amount) to convert it to a number.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to rounding

How to round a numpy array? How to pad a string with leading zeros in Python 3 Python - round up to the nearest ten How to round a Double to the nearest Int in swift? Using Math.round to round to one decimal place? How to round to 2 decimals with Python? Rounding to 2 decimal places in SQL Rounding to two decimal places in Python 2.7? Round a floating-point number down to the nearest integer? Rounding BigDecimal to *always* have two decimal places

Examples related to decimal-point

Round to at most 2 decimal places (only if necessary) Int to Decimal Conversion - Insert decimal point at specified location Integer.valueOf() vs. Integer.parseInt() How to change the decimal separator of DecimalFormat from comma to dot/point? Decimal separator comma (',') with numberDecimal inputType in EditText How to print a float with 2 decimal places in Java? Javascript: formatting a rounded number to N decimals Formatting a number with exactly two decimals in JavaScript Leave only two decimal places after the dot In jQuery, what's the best way of formatting a number to 2 decimal places?