1
This question is more out of curiosity, I’ve already answered the problem in my code.
I made a money mask using javascript, it was working perfectly, until I entered the value 4.9.
Debugging the code found that the problem was multiplying the value 4.9 by 100, the result of this multiplication gave:
490.00000000000006
What made my mask "bugger".
Other values like 4.8 the result is shown correctly, like:
480
Follow the code below to illustrate:
alert(4.9*100);
//Sem problemas
alert(4.8*100);
//Outro exemplo mais grave
alert(4.6*100);
My question is this, why is there this strange behavior in Javascript? I did the same multiplication using php and it worked normally.
And for those who had the same problem and just want to solve, I solved it in the following way:
var valor = 4.9;
resultado = (valor * 100).toFixed(2);
alert(valor);
var valor = 4.6;
resultado = (valor * 100).toFixed(2);
alert(valor);
Briefly, calculations with floating point numbers are not exact
– Costamilam
Would that be? https://answall.com/questions/14728/realizes%C3%A7%C3%A3o-de-floating-point-in-javascript-with-precis%C3%A3o-absolute
– hkotsubo
this is an old known number rounding problem in javascript, has this interesting question in the OS in English: how-to-Deal-with-floating-point-number-Precision-in-javascript
– Ricardo Pontual