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

7

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 equal 2.

How do I get this result?

    
asked by anonymous 02.09.2014 / 20:00

1 answer

11

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 a division of integers, an error may occur indicating incompatibility between decimal and double, in this case, you must force the result to be of type double, eg:

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

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

    
02.09.2014 / 20:03