C# - Round float every time down

Viewed 21930

How to round a floating point number each time to nearest integer, but only down way. I need the fastest method.

So that float 1.2 will be 1 and 1.8 will be 1 too.

1.2f will be 1.0f

1.8f will be 1.0f

Thanks!

5 Answers

OP asked for the fastest way. Casting to int rounds towards zero so depending on the range you can add a value to make it positive, cast to an int and subtract the same value eg.

float a = -5.2f;
float b = (int)(a + 1000) - 1000;

// b = -6.0f

I did some benchmarks and this method is at least twice as fast as using Math.Floor().

Related