Let's say I have a set of float
numbers, each with an int
value of Significant Figures.
What is the simplest and fastest C# method to find the minimum significant step (as a power of 10) for each value?
Value | Significant Figures | Expected Result |
---|---|---|
1.0123 | 3 | 0.01 |
1.0123 | 4 | 0.001 |
4525 | 2 | 100 |
0.007589 | 1 | 0.001 |
42 | 1 | 10 |
*In bold it's marked the Significant Figures of each Value.
I am tempted to use Math.Log10()
somehow, but I cannot yet figure out how.
One solution:
static float MinimumSignificantStep(float number, int significantFigures)
=> (float)Math.Pow(10, Math.Floor(Math.Log10(Math.Abs(number))) - significantFigures + 1);
I wouldn't be surprised if there were much faster solutions out there.
Keep in mind floating points numbers can be surprising because they're stored as binary numbers multiplied by a power of two, which doesn't always match up nicely with the powers of 10 we usually use. So expect 0.999999, 0.0001 or similar numbers close to the edges to end up with a "wrong" number of digits.