2

I have an invoice page in ASP.NET MVC.

I am calculating GST.

In javascript this the result.

165.45 * 0.1 = 16.544999999999998

In C# I get

165.45 * 0.1 = 16.545

These round differently

I want to round both to 2 decimal places but they give different answers

Javascript = 16.54

C# = 16.55 Which is what I want.

Any ideas how to get them the same??

Arsen Mkrtchyan
  • 49,896
  • 32
  • 148
  • 184
Malcolm
  • 12,524
  • 28
  • 89
  • 125

2 Answers2

3

In C# if you're using double, you're not really getting 16.55 - it may print out to that, but that's not the real value. In both cases you should be using a decimal-based type instead of a binary-based type. In C# that's easy - you can use the decimal (aka System.Decimal) type. I don't know if there's an equivalent in JavaScript, unfortunately.

You should probably read up on binary floating point and decimal floating point to understand why this is important. (Those are .NET-focused articles, but the principles apply to JS too.)

For currency values, one way to avoid this being a problem is to use integers to start with - keep the number of pennies (cents, whatever) in your value, and then display it by just writing out (number / 100) + "." + (number % 100) (using a different decimal separator if necessary). I strongly suspect you'll find this the best way to get consistent and predictable results for this particular situation.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • There is no `decimal` equivalent in JavaScript. All JavaScript numbers are IEEE-754 doubles behind-the-scenes. – LukeH Aug 16 '10 at 08:54
  • @LukeH: Are there any third-party libraries providing something like Java's BigDecimal? – Jon Skeet Aug 16 '10 at 08:57
  • There's BigDecimal for JavaScript, which I think is an attempt at a direct port of the Java version. I have no idea whether it's any good or not. http://freshmeat.net/projects/js_bigdecimal – LukeH Aug 16 '10 at 09:12
  • @LukeH: Thanks. I suspect that the "use integers and division/modulus by 100" is the simplest answer in this case. – Jon Skeet Aug 16 '10 at 09:31
  • Definitely. That's what I resort to on the rare occasions when I do something like this. – LukeH Aug 16 '10 at 09:54
1

I suspect there might not be a consistent way to round numbers in Javascript, since browsers use different JS engines that behave differently.

That said, you should do mission-critical calculations on the server side.
Never, ever trust client input.

quantumSoup
  • 27,197
  • 9
  • 43
  • 57