Math.Floor
This C# method rounds down. Found in the System
namespace, it operates on types such as decimal or double
. It reduces the value to the nearest integer.
Floor()
is straightforward, but useful, when it is called for in C# programs. It can be used alongside Math.Ceiling
for related functionality.
Consider a number like 123.456—this number has 3 digits past the decimal place. When we call Floor()
on it, we get 123—the fractional part is deleted.
Input: 123.456 Floor: 123
Floor()
is available on the Math type. It implements the mathematical floor function, which finds the largest integer "not greater" than the original number.
Floor
method being used on doubles that would be rounded down or rounded up with the Math.Round
method.Floor
can be useful when rounding numbers that are part of a larger representation of another number.using System; // // Two values. // double value1 = 123.456; double value2 = 123.987; // // Take floors of these values. // double floor1 = Math.Floor(value1); double floor2 = Math.Floor(value2); // // Write first value and floor. // Console.WriteLine(value1); Console.WriteLine(floor1); // // Write second value and floor. // Console.WriteLine(value2); Console.WriteLine(floor2);123.456 123 [floor] 123.987 123 [floor]
When given a positive number, Floor()
erases the digits after the decimal place. With a negative number, Floor
erases the digits and increases the number's negativity by 1.
Math.Floor
on a negative number will still decrease the total number. This means it will always become smaller.Decimal
Math.Floor
can be used with the decimal type—the decimal.Floor
static
method is immediately called into. It is sometimes clearer to directly use decimal.Floor
.
We looked at the Math.Floor
method. This method is useful when you are trying to represent ratios and percentages and do not want the figures to add up to greater than 1 or 100%.