Feb 7, 2013

Rounding a number to two decimal places in Javascript / Node JS

Posted Feb 7, 2013
Rounding numbers with decimals in Javascript is not straightforward. Javascript has a utility Math.round but it only rounds to the nearest integers. Some uses toFixed function e.g. (2.55555).toFixed(2) but it doesn't work consistently across all browsers, sometimes it just truncates the value which makes it troublesome for computations.

Creating a simple function for rounding numbers to two decimals in Javascript should be easy:

function roundTo2Decimals(numberToRound) {
  return Math.round(numberToRound * 100) / 100
}

//test
roundTo2Decimals(2.55555555);

If you want to use a library, numeraljs is a good one. It also formats numbers with commas. Very useful.


No comments:

Post a Comment