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




On the 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