EN
C# / .NET - Math.Floor() method example
0
points
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 |
|
Parameters | number - double or decimal value (primitive value). |
Result |
Rounded down If If If |
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
}
}