Malcolm
Malcolm

Reputation: 12864

Javascript rounding v c# rounding

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??

Upvotes: 2

Views: 240

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500185

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.

Upvotes: 3

quantumSoup
quantumSoup

Reputation: 28132

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.

Upvotes: 1

Related Questions