Search code examples
c#string-interpolation

Using string interpolation in C# to print floating point values


I'm trying to use string interpolation to print a floating point number to 3 decimal places.
Console.Writeline( $"{3.2, 8: F3}" ); However, this is printing "F3" in a field width of 8. Why is this happening. For example, Console.WriteLine($"{3.2M, 8: C2}"); accurately prints as $3.20 in a string field width of 8.


Solution

  • The space after the colon : causes the issue, you need to be careful about this in format strings:

    Console.Writeline( $"{3.2, 8:F3}");  // Outputs 3.200
    

    Test it in DotnetFiddle