ToFixed does not work as expected (please provide a reason not an alternative)
toFixed()
the function reacts differently to float values. For example:
var a = 2.555;
var b = 5.555;
console.log(a.toFixed(2)); /* output is 2.56 */
console.log(b.toFixed(2)); /* output is 5.55 */
For results 2.555 / 3.555 (2.56 / 3.56)
and
For other values ββ(not necessarily all values) # .55 is displayed (# represents any number)
I am confused, can anyone help me.
Thanks in advance.
source to share
Javascript uses binary floating point representation for numbers (IEEE754). Using this representation, the only numbers that can be represented exactly have the form n / 2 m where both n
and m
are integers.
Any number that is not rational, where the denominator is an integral power of two, cannot be accurately represented because in binary it is a periodic number (it has infinite binary digits after the dot).
The number 0.5
(i.e. 1/2) is fine, (in binary it's easy 0.1β
), but for example 0.55
(i.e. 11/20) cannot be accurately represented (in binary 0.100011001100110011ββ¦
i.e. 0.10(0011)β
with the last part 0011β
repeating infinite time).
If you need to perform any calculations where the result depends on exact decimal numbers, you need to use exact decimal notation. A simple solution, if the number of decimal places is fixed (e.g. 3), is to store all values ββas integers by multiplying them by 1000 ...
2.555 --> 2555
5.555 --> 5555
3.7 --> 3700
and adjusting the calculations when doing multiplications and divisions respectively (for example, after multiplying two numbers, you need to divide the result by 1000).
The IEEE754 double precision format is precise with integers up to 9,007,199,254,740,992 and that's good enough for prices / values ββ(where rounding is most often a problem).
source to share
toFixed () depending on browser rounding or saving.
Here is the solution to this problem, check the "5" at the end
var num = 5.555;
var temp = num.toString();
if(temp .charAt(temp .length-1)==="5"){
temp = temp .slice(0,temp .length-1) + '6';
}
num = Number(temp);
Final = num.toFixed(2);
Or the reuse function would look like
function toFixedCustom(num,upto){
var temp = num.toString();
if(temp .charAt(temp .length-1)==="5"){
temp = temp .slice(0,temp .length-1) + '6';
}
num = Number(temp);
Final = num.toFixed(upto);
return Final;
}
var a = 2.555;
var b = 5.555;
console.log(toFixedCustom(a,2));
console.log(toFixedCustom(b,2));
source to share