Search code examples
c#stringformat-string

Format Strings -- Pad a double left and right


I am almost to embarrassed to ask this very basic question, but:

How do you print the following only using format strings?

42.315 -->  42.315000
-4.2   -->  -4.200000
315.42 --> 315.420000

if it was not noticable: I require a padding with spaces before the comma/dot and a zero-padding after the comma/dot


I have the following code to pad the following zeros:

double v1 = 42.315;

return string.Format("v1: {0:F14}", v1);

And I would normally use <string>.PadLeft(18, ' ') to pad the left side of the string with zeros.
I do, however, want to avoid string::PadLeft(int, char) and solve this issue purely with string::format(string, params object[]).


I am pretty sure, that this has been asked about a hundred times here - though I was unable to find the question(s). But feel free to mark it as a duplicate [only if it is one - of course] ...


Solution

  • Add the padding between the index and the colon:

    string.Format("v1: {0,18:F14}", v1)
    

    Result:

    v1:  42.31500000000000
    

    This is documented here.