String.Format - How can I format to x digits (regardless of decimal place)?

Simon picture Simon · Aug 3, 2012 · Viewed 8.5k times · Source

I need to format a floating point number to x characters (6 in my case including the decimal point). My output also needs to include the sign of the number

So given the inputs, here are the expected outputs

1.23456   => +1.2345

-12.34567 => -12.345

-0.123456 => -0.1234

1234.567  => +1234.5

Please assume there is always a decimal place before the last character. I.e. there will be no 12345.6 number input - the input will always be less than or equal to 9999.9.

I'm thinking this has to be done conditionally.

Answer

Jonathon Reinhart picture Jonathon Reinhart · Aug 3, 2012

You mention "x characters". So we can simplify that to "x-1 digits", and just write code that shows x digits.

I think passing the "G" numeric format specifier to Double.ToString() is as close to built-in as you can get.

double d = 1234.56789;
string s = d.ToString("G6");           // "1234.57"

So we just expand that to manually add the "+" at the front:

if (d > 0)
    s = "+" + s;

Putting it all together in an extension method:

EDIT: Includes optional parameter to truncate

public static string ToStringWithSign(this double d, int digits, bool truncate = false)
{
    if (truncate) {
        double factor = Math.Pow(10, digits - 1);
        d = Math.Truncate(d * factor) / factor;
    }

    string s = d.ToString("G" + digits);
    if (d > 0)
        s = "+" + s;
    return s;
}

Results:

(1234.56789).ToStringWithSign(4);      // "+1235"
(1234.56789).ToStringWithSign(5);      // "+1234.6"
(1234.56789).ToStringWithSign(6);      // "+1234.57"
(-1234.56789).ToStringWithSign(6);     // "-1234.57"

(1.2345678).ToStringWithSign(6);       // "+1.23457"
(1.2345678).ToStringWithSign(6, true); // "+1.23456"