Javascript floating point problem - rounding problem?

I have a problem with my client side script without calculating the same values ​​as my server side code:

For instance:

var x = (2.85 * .1); alert(x); 

This gives the figure 0.28500000000000003

However, my server side code (C #) computes the numbers 0.285, which when rounded to 2 decimal places give 0.28

If I try to round 0.28500000000000003 to 2 decimal places, I get 0.29.

How do I get my Javascript to create a shape that matches my server code.

It looks like I need to go through 2 rounds of rounding - first, to remove trailing 3, and then round to the desired decimal places.

For instance:

 var x = 0.2850000000003; x = parseFloat(x.toFixed(3)) x = x.toFixed(2) alert(x); 

Is this the best workaround?

(This is a reformulation of the question that I opened and deleted earlier)

+6
source share
3 answers

.Net uses banker rounding . If the number is at the midpoint of rounding, for example. 2.5, then the number is rounded to the nearest even number, in this case 2. Rounding thus eliminates the offset introduced by rounding up.

You can use bankers rounding in javascript using the snippet at http://snippets.dzone.com/posts/show/1305 .

+5
source

Your C # code uses the decimal type of base 10, which by default uses bankers rounding. Javascript code uses base 2 floating point arithmetic. These two forms of computer arithmetic will inherently give different results. The solution should be to use the same arithmetic methods in both codes.

+2
source

There is no number like 0.285 in double. Here are two numbers I see when testing in JRuby:

 irb(main):002:0> java.math.BigDecimal.new(0.285).to_s => "0.284999999999999975575093458246556110680103302001953125" irb(main):003:0> java.math.BigDecimal.new(2.85 * 0.1).to_s => "0.28500000000000003108624468950438313186168670654296875" 

Obviously, it seems that JRuby has the same behavior as your JS. :-)

0
source

Source: https://habr.com/ru/post/896401/


All Articles