Question

I'm looking for an implementation of floor(x) in C# so that it would match the C++ version.

floor of 2.3 is 2.0
floor of 3.8 is 3.0
floor of -2.3 is -3.0
floor of -3.8 is -4.0

Since a C++ reviewer will be checking my code, what implementation of floor is reasonable in C# so that he doesn't pull out his (last remaining) hairs?

Was it helpful?

Solution

You can use the Math class. There are many overloaded form of Math.Floor

  1. Math.Floor(Double)
  2. Math.Floor(Decimal)

Simple Usage :

Math.Floor(2.3) // == 2.0
Math.Floor(3.8) // == 3.0
Math.Floor(-2.3) // == -3.0
Math.Floor(-3.8) // == -4.0

OTHER TIPS

Just use Math.Floor. It rounds towards negative infinity, as does the C++ floor. From the documentation:

The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding toward negative infinity. In other words, if d is positive, any fractional component is truncated. If d is negative, the presence of any fractional component causes it to be rounded to the smaller integer.

The math library does what you need. Docs are here. More importantly, the term floor is defined to always behave as you describe. See wikipedia for details on the mathematical floor function

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top