Home | Contact Us

CSharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript

C# Math.Floor Method

This C# tutorial shows how to use the Math.Floor method in the .NET Framework.

Math.Floor rounds down. It operates on types such as decimal or double.

It reduces the value to the nearest integer. The Floor method is straightforward, but useful, when it is called for in programming.


Example. First, the Floor method is found in the base class library and is available in 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.


C# program that uses Math.Floor

using System;

class Program
    static void Main()
	// 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.
	// Write second value and floor.


123     [floor]
123     [floor]

In the example, the two numbers 123.456 and 123.987 are rounded down to the nearest integer. 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.

Discussion. The Math.Floor method when given a positive number will erase the digits after the decimal place. But when it receives a negative number, it will erase the digits and increase 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.

Next, the Math.Floor method can be used on the 128-bit decimal type. When you call Math.Floor with this data type, the decimal.Floor static method is immediately called into. It is sometimes clearer to directly use decimal.Floor.

DecimalStatic Method

Summary. We looked at the Math.Floor method in the base class library. This method is occasionally 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%.

Tip: We can use Math.Floor on the double type or decimal type, which calls into the decimal.Floor method.