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.
Method notes. Floor() is straightforward, but useful, when it is called for in C# programs. It can be used alongside Math.Ceiling for related functionality.
Input and output. 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
Example. Floor() is available on the Math type. It implements the mathematical floor function, which finds the largest integer "not greater" than the original number.
Next This example shows the Floor method being used on doubles that would be rounded down or rounded up with the Math.Round method.
Info In the example, the two numbers 123.456 and 123.987 are rounded down to the nearest integer.
And This means that regardless of how close they are close to 124, they are rounded to 123.
Note 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]
Discussion. 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.
So Using 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.
Summary. 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%.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.