6

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

For example:

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

This gives a figure of 0.28500000000000003

However my server side code (C#) calculates a figures of 0.285 which when rounded to 2 decimal places gives 0.28

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

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

It looks like I have to go through 2 lots of rounding - firstly to remove the trailing 3, then the rounding to the required decimal places.

For example:

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

Is this the best workaround?

(this is a re-wording of a question I opened and deleted earlier)

3
  • 0.285 should not get rounded to 0.28. You must be doing some other operation in C# Commented Sep 1, 2011 at 12:00
  • 1
    In C# try string str = (2.85 * .1).ToString("R") (R means RoundTrip, it will show all the decimals the double has). You'll see the ,...0003 Commented Sep 1, 2011 at 12:02
  • Is your C# code using decimal or floating point? Commented Sep 1, 2011 at 12:02

3 Answers 3

5

.Net uses banker's rounding. If a number is at the rounding midpoint e.g. 2.5 then the number is rounded to the closest even number, in this case 2. Rounding in this manner eliminates the bias introduced by rounding upwards.

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Smirkin. This issue has had me chasing around in circles.
@FloatLeft You still have the problem that floats are quite useless when you need something precise :-) I hope that the equal un-preciseness of C# and JS is good enough for you :-) :-)
I'm going to use MidpointRounding.AwayFromZero in my C# code.
2

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

Comments

0

There is no such number as 0.285 in double. Here are the 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 JRuby has the same behaviour as your JS. :-)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.