I’m trying to write an algorithm to find the minimum number of precision digits to show at least one significant figure using .Net string formatter.
eg.
Value Precision wanted:
----- -----------------
10 0
1 0
0.1 1
0.99 1
0.01 2
0.009 3
(don’t care about further digits, only the first, hence 0.99 only need a precision of 1.)
The best I can come up with is:
int precision = (int)Math.Abs(Math.Min(0, Math.Floor(Math.Log10(value))));
This works fine but I can’t help thinking there’s a more elegant solution. Can any maths gurus help me out?
Slightly shorter: