N
N
Nadoedalo2014-02-06 16:10:41
JavaScript
Nadoedalo, 2014-02-06 16:10:41

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

7 answer(s)
Y
Yuri Lobanov, 2014-02-06
@Nadoedalo

alert(Math.round((2587.845 * 100).toFixed(1))/100)

N
nekipelov, 2014-02-06
@nekipelov

Use whole numbers. 1 ruble and 10 kopecks are represented as 110 or 1100 depending on the required accuracy.

R
Rsa97, 2014-02-06
@Rsa97

Math.round(299*8655/10)/100

A
Anton Anton, 2014-02-06
@Fragster

Decimal type emulation option through calculations in thousandths of a ruble and rounding at each stage.

A
Anton Anton, 2014-02-06
@Fragster

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.

A
Anton Anton, 2014-02-06
@Fragster

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)

M
Mikhail Shatilov, 2014-02-06
@iproger

Sometimes customers do not add a penny.
So always add

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question