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

Asked

Viewed 9,757 times

8

I have the following account:

var NumeroDePaginas = NumeroDeItens / 32;

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

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

How to get this result?

1 answer

12


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

Remark: 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 double, example:

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

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

  • 1

    Thank you Diego. See if you can help me even more... I’m not being able to use the expression Convert.Toint32(Math.Ceiling(3 / 32)). Says The call is ambiguous between the following methods or properties: 'System.Math.Ceiling(decimal)' and 'System.Math.Ceiling(double)'

  • 1

    When you divide two integers and these, have broken result, automatically the result is converted to decimal. You can solve the problem by forcing the conversion to be done in double, just use so Math.Ceiling(3 / 32d). This 32d indicates that 32 becomes double type, so the result will also be double, so there will be no error when calling the method.

  • 1

    That’s right, I was just going to say that I did, thank you very much! I think this observation may be useful for someone in the future. If you want to complement the answer would be nice.

  • You are right John Paul, I added a remark in the reply. Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.