Answer the question
In order to leave comments, you need to log in
JS computer inaccuracy
There is a problem - sometimes customers do not add a penny.
For example, when you try to multiply 299 by 8.655 (dollars and exchange rate), you get 2587.845. To round correctly, Math.round(x * 100)/100 is used. The problem arises when you multiply 2587.845 by 100, you get 258784.49999999997, which when rounded up gives you 2587.84.
Please advise how you solve these problems? Some kind of math library that treats numbers as strings? mathjs doesn't help.
The current solution is to move important calculations to a more accurate backend.
Example Code
var x = 299 * 8.655;
console.log(x, Math.round(x * 100)/100, x * 100)
>>> 2587.845, 2587.84, 258784.49999999997
Answer the question
In order to leave comments, you need to log in
Use whole numbers. 1 ruble and 10 kopecks are represented as 110 or 1100 depending on the required accuracy.
Decimal type emulation option through calculations in thousandths of a ruble and rounding at each stage.
well, yes - in your code I get it right in firebug:
var x = 2587.845*100;
x = Math.round(100*x)/100
console.log(x);
>>> var x = 2587.845*100; x = Math.round(100*x)/100 console.log(x);
258784.5
Look for the error more carefully.
I found a wonderful library:
https://github.com/guipn/sinful.js/wiki/API#math
With its help it will be like this:
Math.div(Math.mul(100,x), 100)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question