Bagzli
Bagzli

Reputation: 6579

C# - Decimal to integer and round depending on value

I'm trying convert a decimal into integer and want to round the value up or down depending on the situation.

Basically example is:

Whatever I found on the internet always rounds down or always rounds up, never makes a judgment call based on the numbers.

Upvotes: 0

Views: 1320

Answers (4)

PaulB
PaulB

Reputation: 24382

Does Math.Round(d) do what you require?

Return Value: The integer nearest parameter d. If the fractional component of d is halfway between two integers, one of which is even and the other odd, the even number is returned. Note that this method returns a Decimal instead of an integral type.

Check out the Round reference page

Upvotes: 1

Simon Bull
Simon Bull

Reputation: 881

Math.Round(value) should do what you want. Examples console app code to demonstrate:

Console.Write("12 / 3 = ");
Console.WriteLine((int)Math.Round(12d / 3d));
Console.WriteLine();

Console.Write("11 / 3 = ");
Console.WriteLine((int)Math.Round(11d / 3d));
Console.WriteLine();

Console.Write("10 / 3 = ");
Console.WriteLine((int)Math.Round(10d / 3d));
Console.WriteLine();

Console.Write("9 / 3 = ");
Console.WriteLine((int)Math.Round(9d / 3d));
Console.WriteLine();

Console.ReadKey();

Upvotes: 1

the_lotus
the_lotus

Reputation: 12748

You could try this

Math.Round(d, 0, MidpointRounding.AwayFromZero)

Sometime, people add 0.5 to the number before converting to int.

Upvotes: 0

Aasmund Eldhuset
Aasmund Eldhuset

Reputation: 37950

If x is the number you want to round and you want the "normal" rounding behavior (so that .5 always gets rounded up), you need to use Math.Round(x, MidpointRounding.AwayFromZero). Note that if you are actually computing fractions and the numerator and denominator are integers, you need to cast one of them to double first (otherwise, the division operator will produce an integer that is rounded down), and that if you want the result to be an int, you need to cast the result of Round():

int a = 5;
int b = 2;
double answer = (int) Math.Round(a / (double) b, MidpointRounding.AwayFromZero);

Upvotes: 4

Related Questions