The problem:
Given an input float (value
), round another float (anotherValue
) so it has the same significant figures as the first float (value
).
What I have tried so far:
private static void Test()
{
var value = 0.12345f;
// ?? Strategy suggested by this post: http://stackoverflow.com/questions/3683718/is-there-a-way-to-get-the-significant-figures-of-a-decimal
var significantFigures = decimal.GetBits((decimal)value);
var anotherValue = 3.987654321;
// ERROR: Argument 2: cannot convert from int[] to int
var resultValue = (float) SetSignificantFigures((double)anotherValue, significantFigures.Length);
// Desired result: resultValue = 3.988
}
This is the definition of SetSignificantFigures
:
// Function suggested by this post: http://stackoverflow.com/questions/374316/round-a-double-to-x-significant-figures
public static double SetSignificantFigures(double d, int digits)
{
double scale = Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(d))) + 1);
return scale * Math.Round(d / scale, digits);
}
Blocking point: since decimal.GetBits
returns int[]
, I don't know how to proceed (or if it is the correct strategy).