Hi
I know you can round a float down to an int, but is there a way to round down a float, e.g. 0.530223F, down to 0.5F?
Thanks!
Hi
I know you can round a float down to an int, but is there a way to round down a float, e.g. 0.530223F, down to 0.5F?
Thanks!
Look for ‘RoundTo’, ‘CeilTo’ and ‘FloorTo’
/// <summary>
/// roundTo some place comparative to a 'base', default is 10 for decimal place
///
/// 'place' is represented by the power applied to 'base' to get that place
/// </summary>
/// <param name="value">the value to round</param>
/// <param name="place">the place to round to</param>
/// <param name="base">the base to round in... default is 10 for decimal</param>
/// <returns>The value rounded</returns>
/// <remarks>e.g.
///
/// 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011
///
/// roundTo(2000/7,-3) == 0
/// roundTo(2000/7,-2) == 300
/// roundTo(2000/7,-1) == 290
/// roundTo(2000/7,0) == 286
/// roundTo(2000/7,1) == 285.7
/// roundTo(2000/7,2) == 285.71
/// roundTo(2000/7,3) == 285.714
/// roundTo(2000/7,4) == 285.7143
/// roundTo(2000/7,5) == 285.71429
///
/// roundTo(2000/7,-3,2) == 288 -- 100100000
/// roundTo(2000/7,-2,2) == 284 -- 100011100
/// roundTo(2000/7,-1,2) == 286 -- 100011110
/// roundTo(2000/7,0,2) == 286 -- 100011110
/// roundTo(2000/7,1,2) == 285.5 -- 100011101.1
/// roundTo(2000/7,2,2) == 285.75 -- 100011101.11
/// roundTo(2000/7,3,2) == 285.75 -- 100011101.11
/// roundTo(2000/7,4,2) == 285.6875 -- 100011101.1011
/// roundTo(2000/7,5,2) == 285.71875 -- 100011101.10111
///
/// note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed
/// because we are rounding 100011.1011011011011011 which rounds up.</remarks>
publicstaticfloatRoundTo(float value,int place,uint@base)
{
if(place ==0)
{
//'if zero no reason going through the math hoops
return(float)Math.Round(value);
}
elseif(@base==10&& place >0&& place <=15)
{
//'Math.Round has a rounding to decimal spaces that is very efficient
//'only useful for base 10 if places are from 1 to 15
return(float)Math.Round(value, place);
}
else
{
float p =(float)Math.Pow(@base, place);
return(float)Math.Round(value * p)/ p;
}
}
You’ll notice that in the implementation for RoundTo I talk about how System.Math.Round actually has this for places 1->15 that is very efficient. This implementation I have here uses that for those cases, but then does it my way for all others.
Excellent, thanks for this!