tags:

views:

57

answers:

2

Why does the following code:

Console.WriteLine(String.Format("{0:C0}", 2170/ 20));

yield "$109", while doing

Console.WriteLine(Math.Round(2170 / 20));

gives me 108?

How can I get 2170 / 20 give me 109?

+4  A: 

When you divide to values of integral type, such as 2170 and 20, the runtime performs an integer division and discards (truncates) the decimal.

If you change one of the operands to a float, double, or decimal (eg, 2170.0 / 20, or 2170 / 20m), it will perform a floating-point division, as you would expect.

Therefore, you need to change it to

Console.WriteLine(Math.Round(2170.0 / 20));

EDIT

Like this:

Math.Round(2170m / 20, MidpointRounding.AwayFromZero)
SLaks
@SLacks That's what I ended up implementing, however, I wanted to know why. Is the issue that String.Format("{0:C0}"... method uses MidpointRounding.AwayFromZero internally?
AngryHacker
A: 

Try Math.Round(2170.0 / 20.0)

Robert Paulson