How to round decimals up to get an integer in C#?

Question:

I have the following account:

var NumeroDePaginas = NumeroDeItens / 32;

When I use Math.Round it rounds both up and down. But whenever there is any decimal value I want to return an integer value rounded up.

Example: If NumeroDeItens / 32 is equal to 1.01, NumeroDePaginas will be equal to 2.

How to get this result?

Answer:

Use Math.Ceiling(), example:

var valorArredondado = Math.Ceiling(1.01);

Example taken from MSDN:

double[] values = {7.03, 7.64, 0.12, -0.12, -7.1, -7.6};
Console.WriteLine("  Value          Ceiling          Floor\n");
foreach (double value in values)
    Console.WriteLine("{0,7} {1,16} {2,14}", 
                 value, Math.Ceiling(value), Math.Floor(value));

// The example displays the following output to the console: 
//         Value          Ceiling          Floor 
//        
//          7.03                8              7 
//          7.64                8              7 
//          0.12                1              0 
//         -0.12                0             -1 
//          -7.1               -7             -8 
//          -7.6               -7             -8

Note: When using Math.Ceiling(), if there is an integer division, an error may occur indicating incompatibility between decimal and double, in this case, you must force the result to be of type double, for example:

var valorArredondado = Math.Ceiling(3 / 32d);

Where the letter d after the number indicates that 32 will be of type double.

Scroll to Top