Number toFixed(2) in Js if decimal have - JavaScript - SitePoint Forums | Web Development & Design Community
Javascript tofixed
types - How can I round a number in JavaScript? .toFixed() returns a string? - Stack Overflow
This is why you should not using "toFixed" to rounding a number to the nearest integer.
Videos
Number.prototype.toFixed is a function designed to format a number before printing it out. It's from the family of toString, toExponential and toPrecision.
To round a number, you would do this:
someNumber = 42.008;
someNumber = Math.round( someNumber * 1e2 ) / 1e2;
someNumber === 42.01;
// if you need 3 digits, replace 1e2 with 1e3 etc.
// or just copypaste this function to your code:
function toFixedNumber(num, digits, base){
const pow = Math.pow(base ?? 10, digits);
return Math.round(num*pow) / pow;
}
Why isn't this function included in the JavaScript's standard library? Because floating point numbers are hard! Many decimal numbers cannot be directly represented by base-two floats – that's why 0.09 + 0.01 !== 0.1 but 0.09999999999999999. If developers were given a tool which is supposed to round floats to decimal places, they'd (wrongly) assume that it really returns a decimal number, when it in fact returns the closest representable double-precision base-two float.
I've solved this problem by changing this:
someNumber = someNumber.toFixed(2)
...to this:
someNumber = +someNumber.toFixed(2);
However this will convert the number to a string and parse it again, which will have a significant impact on performance. If you care about performance or type safety, check the the other answers as well.
console.log(+(123.455).toFixed(2))
--> The output is 123.45 (wrong)
console.log(Math.round(123.455 * 100) / 100)
--> The output is 123.46 (correct)
-----------------------------------------------------------------------------
Some peoples said "toFixed" is rounding down the number. This is not true.
> +(123.45).toFixed(1)
123.5 (rounding up)
> +(123.445).toFixed(2)
123.44 (rounding down)