Child pages
  • Solution to JavaScript number rounding issues
Skip to end of metadata
Go to start of metadata

Due nature how floating point numbers are stored in JavaScript the native javascript functions doesn't round them correctly.

Let's take 145.575 number and round it to 2 digit after comma precision:

CodeActual ResultCorrect Result
Math.round(145.575 * 100) / 100

145.57

145.58

(145.575).toFixed(2)
145.57145.58

On the http://stackoverflow.com/questions/10015027/javascript-tofixed-not-rounding page I've found interesting solution:

function toFixed(num, precision) {
	return (+(Math.round(+(num + 'e' + precision)) + 'e' + -precision)).toFixed(precision);
} 

It works correctly with any number and precision combination exception number is smaller or equals to 0.0000001.

Related Discussions