简体   繁体   中英

C# Round up and down

I'm counting the results of my database. If it's lower then 50, i want to divide them by 2. Example:

if(CountResults < 50)
{
    //CountResults = 39
    int divided = CountResults / 2; //Results in 19
}

What i want:

if(CountResults < 50)
{
    //CountResults = 39
    int divided = CountResults / 2; //Results in 19,5
    Math.Round(divided, 0);
}

I want to be able to round it upwards and down.

So i get the result 19.5 twice. Once i want it to be 19 , and once to be 20. .

How do i achieve this?

It's not clear how you are going to use your code twice, but if you want to divide integer into two integer parts just subtract first result from totals:

if(CountResults < 50)
{
    //CountResults = 39
    int divided1 = CountResults / 2;        // 19
    int divided2 = CountResults - divided1; // 20
}

First result will use integer division and it will give you result rounded towards zero (19 in your case). Further reading: C# Specification 7.7.2 Division Operator

Second result will give you rest which will be either equal to first result (if there was no rounding), or it will be equal to division rounded from zero (20 in your case).

The rounding part can be accomplished using these 2 nice methods:

Math.Floor brings it to the floor

Math.Celing lifts it to the celing ;)

The calculation part is a little more tricky. This statement:

int divided = CountResults / 2; //Results in 19,5

cannot really be true, or let's say it does not matter what is behind the comma because when it is assigned to the variable int devided it will loose this information and no rounding is anymore required.
When you want a result of type double (meaning eg 19,5 ) and you want to round that result, you need at least one of the parameters of the calculation to be of type double double !

Example

double var1 = 39;

int res_low = (int)Math.Floor(var1 / 2);
int res_high = (int)Math.Ceiling(var1 / 2);

note that writing 2 is implicitly seen by the compiler as int and writing 2.0 is implicitly seen as double . So this would yield the same result:

int var2 = 39;

int res_low2 = (int)Math.Floor(var2 / 2.0);
int res_high2 = (int)Math.Ceiling(var2 / 2.0);

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