86

I have used interpolated strings for messages containing string variables like $"{EmployeeName}, {Department}". Now I want to use an interpolated string for showing a formatted double.

Example

var aNumberAsString = aDoubleValue.ToString("0.####");

How can I write it as an interpolated string? Something like $"{aDoubleValue} ...."

MarredCheese
  • 9,495
  • 5
  • 59
  • 63
MagB
  • 1,781
  • 4
  • 23
  • 51
  • 1
    Note: string interpolation uses current culture. For insensitive interpolation, you can use Invariant from System.FormattableString: `Invariant($"at {num}")`. See https://stackoverflow.com/questions/33203261/what-is-the-default-culture-for-c-sharp-6-string-interpolation – ANeves thinks SE is evil Nov 21 '18 at 19:52

2 Answers2

131

You can specify a format string after an expression with a colon (:):

var aNumberAsString = $"{aDoubleValue:0.####}";
lc.
  • 105,606
  • 20
  • 147
  • 176
  • 16
    The list of possible formatting specifications can be found [here (for custom formats)](https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings) and [here (for standard formats)](https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings) – kmote Nov 30 '17 at 18:56
20

A colon after the variable specifies a format,

Console.Write($"{aDoubleValue:0.####}");
Ash Burlaczenko
  • 21,581
  • 14
  • 63
  • 95