2
\$\begingroup\$

I wrote this for an SO question on formatting numbers to specific quantities of significant figures (after all, ), 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}");
}
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$
int e = 0;

You're initializing e to default(int), which is redundant. This would be enough:

int e;

I'm not quite sure why you're incrementing e like this:

while (number >= 10.0)
{
    e += 1;
    number /= 10;
}

Why not just e++;?

And same thing here:

while (e > 0)
{
    number *= 10;
    e -= 1;
}

There's e--; to decrement.

But you know this already:

figures--;

Why? Why are you using both -= 1 and -- in the same method?

figures += 0 - e;

Looks like a pretty convoluted way to do figures -= e;.

And then we get to the return value...

return number.ToString($"f{figures}");

You're using C# 6.0 string interpolation here. A format string. The SO question you linked to has an accepted answer that uses a format string to do all the work: it seems string.Format("{0:G10}", number) would do the formatting part just right - I'd parameterize the length by making a method that builds a format string from the parameter (something like "{0:G" + digits + "}"), and uses that format string to return the formatted string.

I think it would be easier to read and to follow, than the whole logic you got there.

Or, don't use a format string. IMO using a formatted string here defeats the purpose of reinventing the wheel.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Damn, I must have been really tired to make that many mistakes...lol Although I wrote this long before the other SO answer was posted, which is why I used f instead of G. \$\endgroup\$ Sep 10, 2015 at 18:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.