C#6如何使用插值字符串格式化双?

Mag*_*agB 65 c# double string-interpolation c#-6.0

我使用了C#6的一些新功能.用于简单用法的插值字符串(显示包含字符串变量的消息,如$"{EmployeeName},{Department}").

现在我想使用插值字符串来显示格式化的double值.

var aNumberAsString = aDoubleValue.ToString("0.####");
Run Code Online (Sandbox Code Playgroud)

如何将其写为插值字符串?像$"{aDoubleValue} ...."

lc.*_*lc. 100

您可以在带有冒号(:)的表达式后指定格式字符串:

var aNumberAsString = $"{aDoubleValue:0.####}";
Run Code Online (Sandbox Code Playgroud)

  • 可以找到可能的格式规范列表[此处(对于自定义格式)](https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings)和[这里(标准格式)](https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings) (11认同)

Ash*_*nko 17

变量后面的冒号指定格式,

Console.Write($"{aDoubleValue:0.####}");
Run Code Online (Sandbox Code Playgroud)


Raf*_*ael 6

或者像这样:

Console.Write($"{aDoubleValue:f4}");
Run Code Online (Sandbox Code Playgroud)