How do I round numbers to the nearest integer?

13

I have double numbers as

double a = 0.4, b = 0.5;

How do I round up?

    
asked by anonymous 21.12.2013 / 17:59

2 answers

22

For simple rounding, use the Math.Round which receives a double (or decimal) and rounds the nearest integer:

Math.Round(0.4); // 0
Math.Round(0.6); // 1

However, this method has one though: if the number to be rounded is halfway between an integer and another (eg, 0.5 ) it will always round to the even number:

Math.Round(1.5); // 2
Math.Round(2.5); // 2

For greater control over the result, use the overloaded method ( overloaded ) that accepts the additional parameter MidpointRounding ". It is an enumeration, which accepts the following values:

  • AwayFromZero (chooses the integer more "distant" from zero, that is: the greater, if the parameter is positive, the smaller if it is negative)
  • ToEven (chooses the integer pair, similar to the default behavior)

Note that there are cases where the above options are not enough: if you want the number to be rounded toward zero (ie the integer with the absolute value >), and its parameters may include negative numbers, more than one operation may be required. An example would be:

public double PontoMedioDirecaoZero(double d) {
    double absInt = Math.Floor(Math.Abs(d)); // Piso do valor absoluto
    double absDec = Math.Round(Math.Abs(d) - absInt); // Arredondamento do valor absoluto
    return Math.Sign(d) * (absInt + absDec); // "Monta" o resultado final
}
PontoMedioDirecaoZero(-1.5); // -1

A similar strategy may be required if you want to round always (and not only midpoint) down ( Math.Floor ) or Up (

21.12.2013 / 19:14
2
The static class Math contains methods for rounding numbers:

Use Math.Ceil to round up

Math.Ceil(0.5); // 1

Use Math.Round to round off, in this method you can enter a second parameter to determine If 0.5 rounds to 1 or 0 .

Math.Round(0.5, MidpointRounding.AwayFromZero); // 1
Math.Round(0.5);                                // 0

Use Math.Floor to round down

Math.Floor(0.5); // 0

Note that the methods return are double , if you try to convert a very large number to int you will get OverflowException .

    
21.12.2013 / 17:59