Mogli
Mogli

Reputation: 2012

Increasing the value by 1 if it has decimal place?

My scenario is that if

47/15= 3.13333

i want to convert it into 4, if the result has decimal i want to increase the result by 1, right now i am doing this like

        float res = ((float)(62-15) / 15);
        if (res.ToString().Contains("."))
        {
             string digit=res.ToString().Substring(0, res.ToString().IndexOf('.'));
             int incrementDigit=Convert.ToInt16(k) + 1;


        }

I want to know is there any shortcut way or built in function in c# so that i can do this fast without implementing string functions.

Thanks a lot.

Upvotes: 2

Views: 4083

Answers (5)

TelKitty
TelKitty

Reputation: 3156

Something like:

float res = ((float)(62-15) / 15);

int incrementDigit = (int)Math.Ceiling(res);

or

int incrementDigit  = (int)(res  + 0.5f);

Upvotes: 0

Nij
Nij

Reputation: 2078

Another way of doing what you ask is to add 0.5 to every number, then floor it (truncate the decimal places). I'm afraid I don't have access to a C# compiler right now to confirm the exact function calls!

NB: But as others have confirmed, I would think the Math.Ceiling function best communicates to others what you intend.

Upvotes: 0

pyrocumulus
pyrocumulus

Reputation: 9290

You are looking for Math.Ceiling().

Convert the value you have to a Decimal or Double and the result of that method is what you need. Like:

double number = ((double)(62-15) / (double)15);
double result = Math.Ceiling(number);

Note the fact that I cast 15 to a double, so I avoid integer division. That is most likely not what you want here.

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1502156

Do you mean you want to perform integer division, but always rounding up? I suspect you want:

public static int DivideByFifteenRoundingUp(int value) {
    return (value + 14) / 15;
}

This avoids using floating point arithmetic at all - it just allows any value which isn't an exact multiple of 15 to be rounded up, due to the way that integer arithmetic truncates towards zero.

Note that this does not work for negative input - for example, if you passed in -15 this would return 0. you could fix this with:

public static int DivideByFifteenRoundingUp(int value) {
    return value < 0 ? value / 15 : (value + 14) / 15;
}

Upvotes: 9

Piotr Stapp
Piotr Stapp

Reputation: 19820

Use Math.Ceiling Quoting MSDN:

Returns the smallest integral value that is greater than or equal to the specified decimal number.

Upvotes: 5

Related Questions