简体   繁体   中英

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?

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM