Home Communities
IT Knowledge
Inspiration
Languages
EN

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

0 points
Created by:
327

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

``````using System;

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

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

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

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

## 1. Documentation

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

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

``````using System;

public class Program
{
static double FloorPrecised(double number, int precision)
{
double power = Math.Pow(10, precision);

return Math.Floor(number * power) / power;
}

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

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

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

Console.WriteLine( FloorPrecised(    1234, -1 ) ); // 1230
Console.WriteLine( FloorPrecised(    1234, -2 ) ); // 1200
Console.WriteLine( FloorPrecised(    1234, -3 ) ); // 1000

Console.WriteLine( FloorPrecised(  5_000.000_001,  0 ) ); // 5000
Console.WriteLine( FloorPrecised(  5_000.000_001,  6 ) ); // 5000.000001
Console.WriteLine( FloorPrecised(  5_000.000_001, -3 ) ); // 5000
}
}``````

## References

1. Floor and ceiling functions - Wikipedia

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