Home Communities
IT Knowledge
Inspiration
Languages
EN

# C# / .NET - Math.Ceiling() method example

0 points
Created by:
529

The `Math.Ceiling()` function returns an integer value that is greater than or equal to the argument - the result of round-up operation.

``````using System;

public class Program
{
public static void Main(string[] args)
{
Console.WriteLine( Math.Ceiling(  5.0  ));  //  5

Console.WriteLine( Math.Ceiling(  2.49 ));  //  3
Console.WriteLine( Math.Ceiling(  2.50 ));  //  3
Console.WriteLine( Math.Ceiling(  2.51 ));  //  3

Console.WriteLine( Math.Ceiling( -2.49 ));  // -2
Console.WriteLine( Math.Ceiling( -2.50 ));  // -2
Console.WriteLine( Math.Ceiling( -2.51 ));  // -2

Console.WriteLine( Math.Ceiling(  0.999 )); //  1
Console.WriteLine( Math.Ceiling(  1.001 )); //  2
Console.WriteLine( Math.Ceiling( -1.001 )); // -1
}
}``````

## 1. Documentation

 Syntax ``````namespace System { public static class Math { // ... public static decimal Ceiling(decimal number) { ... } public static double Ceiling(double number) { ... } // ... } }`````` Parameters `number` - `decimal` or `double` value (primitive value). Result Rounded up `number` value (primitive value). If input `number` value is equal to `NaN` it returns `NaN`. If input  `number` value is equal to `-Infinity` it returns `-Infinity`. If input  `number` value is equal to `+Infinity` it returns `+Infinity`. Description `Ceiling` is a static method that takes only one parameter and returns a rounded-up value.

## 2. Rounding with precision up-to `n` places example

``````using System;

public class Program
{
static double CeilingPrecised(double number, int precision)
{
double power = Math.Pow(10, precision);
return Math.Ceiling(number * power) / power;
}

public static void Main(string[] args)
{
Console.WriteLine(  CeilingPrecised(  5   , 0  )); // 5
Console.WriteLine(  CeilingPrecised(  5.0 , 0  )); // 5
Console.WriteLine(  CeilingPrecised(  0.5 , 0  )); // 1

Console.WriteLine(  CeilingPrecised(  1.1234, 0  )); // 2
Console.WriteLine(  CeilingPrecised(  1.1234, 1  )); // 1.2
Console.WriteLine(  CeilingPrecised(  1.1235, 2  )); // 1.13
Console.WriteLine(  CeilingPrecised(  1.1235, 3  )); // 1.124

Console.WriteLine(  CeilingPrecised( -1.1234, 0  )); // -1
Console.WriteLine(  CeilingPrecised( -1.1234, 1  )); // -1.1
Console.WriteLine(  CeilingPrecised( -1.1234, 2  )); // -1.12
Console.WriteLine(  CeilingPrecised( -1.1234, 3  )); // -1.123

Console.WriteLine(  CeilingPrecised(  1234, -1  )); // 1240
Console.WriteLine(  CeilingPrecised(  1234, -2  )); // 1300
Console.WriteLine(  CeilingPrecised(  1234, -3  )); // 2000

Console.WriteLine(  CeilingPrecised(  5_000.000_001,  0 )); // 5001
Console.WriteLine(  CeilingPrecised(  5_000.000_001,  6 )); // 5000.000001
Console.WriteLine(  CeilingPrecised(  5_000.000_001, -3 )); // 6000
}
}``````

## References

1. Floor and ceiling functions - Wikipedia

Join to our subscribers to be up to date with content, news and offers.