I wrote this for an SO question on formatting numbers to specific quantities of significant figures (after all, reinventing-the-wheel), anyway, all critiques welcome.
It's pretty easy to use, FormatSignificantFigures(0.123, 2)
should return 0.12
; FormatSignificantFigures(0.123, 5)
should return 0.12300
; FormatSignificantFigures(0.123456, 5)
should return 0.12346
, etc.
public static string FormatSignificantFigures(double number, int figures)
{
int e = 0;
while (number >= 10.0)
{
e += 1;
number /= 10;
}
while (number < 1.0)
{
e -= 1;
number *= 10;
}
figures--;
number = Math.Round(number, figures);
figures += 0 - e;
while (e > 0)
{
number *= 10;
e -= 1;
}
while (e < 0)
{
number /= 10;
e += 1;
}
if (figures < 0)
{
figures = 0;
}
return number.ToString($"f{figures}");
}