7

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!

1
  • 1
    Do you want the result to be of type float or int?
    – Chimera
    Commented Jul 17, 2012 at 23:25

5 Answers 5

19

Math.Floor() is your friend here.

Sample code:

using System;
using System.Text;

namespace math
{
    class Program
    {
        static void Main(string[] args)
        {
            //
            // Two values.
            //
            float value1 = 123.456F;
            float value2 = 123.987F;
            //
            // Take floors of these values.
            //
            float floor1 = (float)Math.Floor(value1);
            float floor2 = (float)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);

            return;        
        }
    }
}
0
4

By casting to an int, you will truncate the decimals

float f = 1.2;
int rounded = (int)f;
1
  • 3
    This will truncate the decimals, as you correctly say. That means it will be rounding up not down if the number is negative.
    – Gigo
    Commented Jul 3, 2014 at 15:53
2

System.Math.Floor(double) should do the trick

1
Math.Ceiling(value)
Math.Floor(value); //your answer
1

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().

  • Math.Floor() is just as fast now it seems.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.