C# - Round float every time down
20,758
Solution 1
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;
}
}
}
Solution 2
By casting to an int, you will truncate the decimals
float f = 1.2;
int rounded = (int)f;
Solution 3
System.Math.Floor(double)
should do the trick
Solution 4
Math.Ceiling(value)
Math.Floor(value); //your answer
Author by
Matej Kormuth
Self-taught programmer with interest for optimization, concurrency and games (both playing & developing). Currently working At IBM. Check out: https://onlineboard.co
Updated on July 09, 2022Comments
-
Matej Kormuth almost 2 years
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!