Math.Ceiling
This C# method rounds up to the next full integer. This means that any number over 1 but under 2 would be rounded to 2.
Math.Ceiling
does not return the same result as rounding a number. Math.Ceiling
is considered a ceiling function in mathematics.
Consider a number like 123.456—we can call Math.Ceiling
on it, and the result is rounded up. And the fractional part is removed.
Input: 123.456 Ceiling: 124
The Math.Ceiling
method in the System
namespace is a static
method that returns a value type. The method receives a double
or decimal type which is resolved at compile-time.
Math.Ceiling
and display the result.Math.Ceiling
are called because the compiler applies overload resolution each time.Math.Ceiling
on a negative floating point, the number will be also be rounded up. The ceiling of -100.5 is -100.using System; // Get ceiling of double value. double value1 = 123.456; double ceiling1 = Math.Ceiling(value1); // Get ceiling of decimal value. decimal value2 = 456.789M; decimal ceiling2 = Math.Ceiling(value2); // Get ceiling of negative value. double value3 = -100.5; double ceiling3 = Math.Ceiling(value3); // Write values. Console.WriteLine(value1); Console.WriteLine(ceiling1); Console.WriteLine(value2); Console.WriteLine(ceiling2); Console.WriteLine(value3); Console.WriteLine(ceiling3);123.456 124 456.789 457 -100.5 -100
We review the implementation of Math.Ceiling
. The overload for Math.Ceiling
that acts on double
types will call into a hidden method that is not represented in managed code.
Math.Ceiling
is likely to be far more optimized than any other method you could develop in C# code.decimal.Ceiling
method is invoked, which calls into the explicit unary negation operator on the decimal type.When we are reporting percentages based on data, using Math.Ceiling
or Floor
is worthwhile. These methods can help make the output more consistent.
Ceiling
and Floor
.Math.Ceiling
always rounds up a number, even when used on a negative number. We noted the implementation and some possible uses of the ceiling and floor functions.