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
Math.Floor() Method in C#
The Math.Floor() method in C# returns the largest integral value that is less than or equal to the specified number. It rounds down to the nearest integer, which is particularly important to understand when working with negative numbers.
Syntax
The Math.Floor() method has two overloads −
public static decimal Floor(decimal val); public static double Floor(double val);
Parameters
-
val − A decimal or double number to be rounded down to the nearest integer.
Return Value
Returns the largest integer less than or equal to val. The return type matches the input type (decimal or double).
Using Math.Floor() with Decimal Numbers
Example
using System;
public class Demo {
public static void Main() {
decimal val1 = 7.10M;
decimal val2 = -79.89M;
decimal val3 = 15.99M;
Console.WriteLine("Math.Floor(7.10) = " + Math.Floor(val1));
Console.WriteLine("Math.Floor(-79.89) = " + Math.Floor(val2));
Console.WriteLine("Math.Floor(15.99) = " + Math.Floor(val3));
}
}
The output of the above code is −
Math.Floor(7.10) = 7 Math.Floor(-79.89) = -80 Math.Floor(15.99) = 15
Using Math.Floor() with Double Numbers
Example
using System;
public class Demo {
public static void Main() {
double val1 = 8.9;
double val2 = 88.10;
double val3 = -31.98;
double val4 = 0.5;
Console.WriteLine("Math.Floor(8.9) = " + Math.Floor(val1));
Console.WriteLine("Math.Floor(88.10) = " + Math.Floor(val2));
Console.WriteLine("Math.Floor(-31.98) = " + Math.Floor(val3));
Console.WriteLine("Math.Floor(0.5) = " + Math.Floor(val4));
}
}
The output of the above code is −
Math.Floor(8.9) = 8 Math.Floor(88.10) = 88 Math.Floor(-31.98) = -32 Math.Floor(0.5) = 0
Comparison with Related Methods
| Method | Description | Example (4.7) | Example (-4.7) |
|---|---|---|---|
| Math.Floor() | Rounds down to nearest integer | 4 | -5 |
| Math.Ceiling() | Rounds up to nearest integer | 5 | -4 |
| Math.Round() | Rounds to nearest integer | 5 | -5 |
| Math.Truncate() | Removes fractional part | 4 | -4 |
Conclusion
The Math.Floor() method always rounds down to the nearest integer, returning the largest integral value less than or equal to the input. Remember that for negative numbers, this means moving further away from zero (e.g., -4.3 becomes -5).
