views:

88

answers:

5
ticketPriceInPence = 7360
percentageToRefund = 100

(int)(Math.Round((ticketPriceInPence * 0.01) * (percentageToRefund * 0.01), 2, MidpointRounding.AwayFromZero) * 100)

This results in : 73.59

(int)(Math.Round((ticketPriceInPence * 0.01) * (percentageToRefund * 0.01) * 100, 2, MidpointRounding.AwayFromZero))

This results in : 73.60

Any idea why it results in different 2 different results

A: 

Because a float is not an exact number. I recommend reading http://en.wikipedia.org/wiki/Floating%5Fpoint. You will see why the result is different.

Maximilian Mayerl
A: 

Long story short. It's because of precision erros when representing float values as binary data. That basically means you can't represent every possible float with 32/64 Bits, so 2.1 in reality is 2.1000000000000001 etc. That's one reason why you should never do something like 2.145 == "other value that should be 2.145".

I suggest reading the article at wikipedia for more detailed information: Wiki Link

Ivo Wetzel
+1  A: 

The simple answer is that it's due to rounding error in equations using floating point numbers. This is because, in general, there is no exact binary representation of a floating point number so all you've got is approximations.

I notice you've got:

(percentageToRefund * 0.01)

in the first equation, and:

(percentageToRefund * 0.01) * 100

in the second.

This latter expression will result in rounding error as you are first dividing by 100 then multiplying by 100 again. The input won't equal the output, the difference depending on machine architecture, OS, language and compiler.

If you're dealing with money you should use decimal type (assuming C#)

ChrisF
A: 

This is due to the finite precision of floating point numbers.

Rik
+4  A: 

It's the old case of floating point numbers not being able to represent decimals exactly.

You seem to be dealing with money here and then you really should consider using decimal.

decimal ticketPriceInPence = 7360;
decimal percentageToRefund = 100;
var result1 = (int)(Math.Round((ticketPriceInPence * 0.01m) * (percentageToRefund * 0.01m), 2, MidpointRounding.AwayFromZero) * 100);
var result2 = (int)(Math.Round((ticketPriceInPence * 0.01m) * (percentageToRefund * 0.01m) * 100, 2, MidpointRounding.AwayFromZero));
Jonas Elfström