PHP round ($ num, 2) and javascript toFixed (2) do not give correct output for this value 53.955
2 answers
Because computers cannot represent floating numbers correctly. It's probably 53.95400000000009 or something like that. The way to deal with this is multiplying by 100, rounding, and then dividing by 100, so the computer only deals with integers.
var start = 53.955,
res1,
res2;
res1 = start.toFixed(2);
res2 = (start * 100).toFixed(0) / 100;
console.log(res1, res2);
//Outputs
"53.95"
53.96
+3
source to share
JAvascript toFixed: The toFixed () method converts a number to a string, keeping the specified number of decimal places.
php round: Returns the rounded val to the specified precision (number of digits after the decimal point). precision can also be negative or zero (default).
Conclusion tofixed doesn't work like php round. accuracy . Specifies the number of decimal digits rounded to.
Javascript function:
function round_up (val, precision) {
power = Math.pow (10, precision);
poweredVal = Math.ceil (val * power);
result = poweredVal / power;
return result;
}
0
source to share