0
I have a simple script that should subtract 3 values. The problem is that I didn’t notice that sometimes the operation should give me a 0 result but gives me a result with a totally strange number. I even did it right on the console with the values and even so gave me this strange result. Ex:
valor_restante = valor_liquido - valor_digitado - valor_acertado;
in this code above the values would be:
valor_restante = 1916.64 - 916.64 - 1000;
The result of the transaction should be 0 but the value is
1.1368683772161603e-13
Can anyone tell you why javascript does it and how to solve it?
This number format is scientific notation (exponential, in potentials of ten), meaning
0.00000000000011368683772161603
- floats are not exact numbers, so whenever you use them for places where you need accuracy, you’re going to have a problem. Read the linked posts above to better understand. If you are going to work with money, try to use pennies instead of real ones, to work with integers. (You can display the comma only at the time of display on the screen) - This is not a feature of Javascript, but of the numeric type used. It happens in virtually any language.– Bacco
I get it. I did
Math.round((valor_liquido - valor_digitado - valor_acertado)*100)/100;
according to what was suggested in the first topic and solved for me. Thank you.– Bruno
It is not the best solution, will give penny error in certain situations. If you’re going to do this you’ll first multiply each one by a hundred and round it up, do the math and then split.
– Bacco