Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
MathF.Ceiling() Method in C# with Examples
The MathF.Ceiling() method in C# is used to find the smallest integer greater than or equal to the specified float value. This method always rounds up to the next integer, even for negative numbers.
Syntax
Following is the syntax −
public static float Ceiling (float val);
Parameters
-
val − A floating-point number whose ceiling value is to be calculated.
Return Value
Returns a float representing the smallest integer that is greater than or equal to the input value.
Using MathF.Ceiling() with Positive Numbers
Let us see an example with positive float values −
using System;
class Demo {
public static void Main() {
float val1 = 12.67f;
float val2 = 30.13f;
float val3 = 5.0f;
Console.WriteLine("Ceiling (12.67f) = " + MathF.Ceiling(val1));
Console.WriteLine("Ceiling (30.13f) = " + MathF.Ceiling(val2));
Console.WriteLine("Ceiling (5.0f) = " + MathF.Ceiling(val3));
}
}
The output of the above code is −
Ceiling (12.67f) = 13 Ceiling (30.13f) = 31 Ceiling (5.0f) = 5
Using MathF.Ceiling() with Negative Numbers
For negative numbers, the ceiling still rounds towards positive infinity −
using System;
class Demo {
public static void Main() {
float val1 = 1.11f;
float val2 = -30.99f;
float val3 = -5.0f;
Console.WriteLine("Ceiling (1.11f) = " + MathF.Ceiling(val1));
Console.WriteLine("Ceiling (-30.99f) = " + MathF.Ceiling(val2));
Console.WriteLine("Ceiling (-5.0f) = " + MathF.Ceiling(val3));
}
}
The output of the above code is −
Ceiling (1.11f) = 2 Ceiling (-30.99f) = -30 Ceiling (-5.0f) = -5
Comparison with Related Methods
| Method | Input: 4.3f | Input: -4.7f | Description |
|---|---|---|---|
| MathF.Ceiling() | 5 | -4 | Rounds up to next integer |
| MathF.Floor() | 4 | -5 | Rounds down to previous integer |
| MathF.Round() | 4 | -5 | Rounds to nearest integer |
Conclusion
The MathF.Ceiling() method always rounds up to the next integer, regardless of whether the input is positive or negative. It returns the smallest integer greater than or equal to the given float value, making it useful for scenarios where you need to ensure a minimum integer boundary.
