114

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
  • 17,541
  • 8
  • 92
  • 91
MagB
  • 2,131
  • 5
  • 28
  • 54
  • 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 Nov 21 '18 at 19:52

3 Answers3

175

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

var aNumberAsString = $"{aDoubleValue:0.####}";
lc.
  • 113,939
  • 20
  • 158
  • 187
  • 28
    The list of possible formatting specifications can be found [here (for custom formats)](https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings) and [here (for standard formats)](https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings) – kmote Nov 30 '17 at 18:56
  • Does not work on my German Windows PC with VS 2022: the double values use comma as decimal separator (instead of a dot). – Alexander Farber Jul 19 '23 at 13:18
26

A colon after the variable specifies a format,

Console.Write($"{aDoubleValue:0.####}");
Ash Burlaczenko
  • 24,778
  • 15
  • 68
  • 99
3

Or like this:

Console.Write($"{aDoubleValue:f4}");
Rafael
  • 1,281
  • 2
  • 10
  • 35