122

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} ...."

1
  • 2
    Note: string interpolation uses current culture. For insensitive interpolation, you can use Invariant from System.FormattableString: Invariant($"at {num}"). See stackoverflow.com/questions/33203261/… Commented Nov 21, 2018 at 19:52

3 Answers 3

190

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

var aNumberAsString = $"{aDoubleValue:0.####}";
Sign up to request clarification or add additional context in comments.

2 Comments

The list of possible formatting specifications can be found here (for custom formats) and here (for standard formats)
Does not work on my German Windows PC with VS 2022: the double values use comma as decimal separator (instead of a dot).
28

A colon after the variable specifies a format,

Console.Write($"{aDoubleValue:0.####}");

Comments

9

Or like this:

Console.Write($"{aDoubleValue:f4}");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.