Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript number.toFixed() not working when number has 3 decimals and fixing to 2 decimals

When trying to round a number with 3 decimals to a number with 2 decimals, toFixed() doesn’t round the latest number correctly. But when I do the same thing with a number with 4 decimals, it does work… I can’t wrap my mind about it how that can be.

I have seen some solutions like Math.round(value * 100) / 100, but then it always rounds down to 2 decimals, while I want a generic function to round, where you can enter the number of decimals to round to.

Currently the function is like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Number.prototype.round = function (precision: number = 2) {
    return Number(this.toFixed(precision));
}

Any ideas on how to solve this issue?

const value = 51.425;
console.log('To fixed with 3 decimals: ', value.toFixed(2));

const value2 = 51.4251;
console.log('To fixed with 4 decimals: ', value2.toFixed(2));

>Solution :

Floating points in JavaScript is broken as @Jaromanda and @dan_pran mentioned.

But the Math.round() solution still works for your use case – it’s just a bit more code:

Number.prototype.round = function (precision = 2) {
  return Math.round(this * 10 ** precision) / 10 ** precision;
}

const value = 51.425;
console.log('Rounded with 3 decimals: ', value.round(2));

const value2 = 51.4251;
console.log('Rounded with 4 decimals: ', value2.round(2));

const value3 = 51.4215;
console.log('Rounded with 4 decimals: ', value3.round(3));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading