0

Code:

double PagesCount = 9 / 6 ;
Console.WriteLine(Math.Round(PagesCount, 0));

I'm trying to round the answer to 9/6(1,5) to 2 but this code snippet always results in 1. How can I avoid that?

kk_Chiron
  • 117
  • 8
  • 2
    Your variable `PagesCount` is already equal to 1, because result of expression `9 / 6` is 1 (integer division in C# also returns integer) – Evk Oct 22 '20 at 10:18
  • Does this answer your question? [Why division is always ZERO?](https://stackoverflow.com/questions/41278585/why-division-is-always-zero) – phuclv Oct 22 '20 at 15:16
  • duplicate: [Why does integer division in C# return an integer and not a float?](https://stackoverflow.com/q/10851273/995714) – phuclv Oct 23 '20 at 23:20

2 Answers2

2

9 / 6 is an integer division which returns an integer, which is then cast to a double in your code.

To get double division behavior, try

double PagesCount = 9d / 6 ;
Console.WriteLine(Math.Round(PagesCount, 0));

(BTW I'm picky but decimal in the .net world refers base 10 numbers, unlike the base 2 numbers in your code)

vc 74
  • 37,131
  • 7
  • 73
  • 89
  • thank you! will it approved later. So would you recommend to just use a decimal? – kk_Chiron Oct 22 '20 at 10:26
  • It really depends on the case, `decimal` computations are slower but more precise. You'd use them for financial calculations for instance (hence the m suffix for money). – vc 74 Oct 22 '20 at 10:28
0

Math.Round is not the problem here.

9.0 / 6.0 ==> 1.5 but 9 / 6 ==> 1 because in the second case an integer division is performed.

In the mixed cases 9.0 / 6 and 9 / 6.0, the int is converted to double and a double division is performed. If the numbers are given as int variables, this means that is enough to convert one of them to double:

(double)i / j ==> 1.5

Note that the integer division is complemented by the modulo operator % which yields the remainder of this division:

9 / 6 ==> 1
9 % 6 ==> 3

because 6 * 1 + 3 ==> 9

Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188