kk_Chiron
kk_Chiron

Reputation: 117

Math.Round for a decimal number

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?

Upvotes: 0

Views: 128

Answers (2)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112259

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

Upvotes: 0

vc 74
vc 74

Reputation: 38179

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)

Upvotes: 2

Related Questions