Bitten by rounding rounding?

Why the following code:

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

gives "$ 109" by doing

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

gives me 108?

How do I get 2170/20 to give me 109?

+3
source share
2 answers

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

If you change one of the operands to float, doubleor decimal(for example, 2170.0 / 20or 2170 / 20m), it will perform floating point separation, as you would expect.

So you need to change it to

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

EDIT

Like this:

Math.Round(2170m / 20, MidpointRounding.AwayFromZero)
+4
source

Try Math.Round (2170.0 / 20.0)

0
source

Source: https://habr.com/ru/post/1759997/


All Articles