I would like to implement a frac function in C# (just like the one in hsl here http://msdn.microsoft.com/en-us/library/bb509603%28VS.85%29.aspx) but since it is for a very processor intensive application i would like the best version possible. I was using something like
public float Frac(float value)
{
return value - (float)Math.Truncate(value);
}
but I'm having precision problems, for example for 2.6f it's returning in the unit test
Expected: 0.600000024f But was: 0.599999905f
I know that I can convert to decimal the value and then at the end convert to float to obtain the correct result something like this:
public float Frac(float value)
{
return (float)((decimal)value - Decimal.Truncate((decimal)value));
}
But I wonder if there is a better way without resorting to decimals...