Insert dynamic number format into interpolated string

心不动则不痛 提交于 2019-12-09 03:44:09

问题


C# 6.0 brings this nifty new formatting operation indicated by a $

Instead of doing this

String lastName = "Doena";
String firstName = "DJ";

Console.WriteLine(String.Format("{1} {0}", lastName, firstName));

you can do this

Console.WriteLine($"{firstName} {lastName}");

But what about number formats. What if I have this:

Decimal price = 9999.95m;
Decimal freebie = 0;

const String format = "#,##0.##";

Console.WriteLine(String.Format("{0:" + format + "}\t{1:" + format + "}", price, freebie));

I tried this:

Console.WriteLine($"{price:"{format}"}\t{freebie:"{format}"}");

and this:

Console.WriteLine($"{price:{format}}\t{freebie:{format}}");

and this:

Console.WriteLine($"{price:format}\t{freebie:format}");

But they either not even compile or do not bring the hoped result.

Any ideas?

Edit Howwie's answer seems to be the reasonable way to go here:

Console.WriteLine($"{price.ToString(format)}\t{freebie.ToString(format)}");

回答1:


Howwie's answer seems to be the reasonable way to go here:

Console.WriteLine($"{price.ToString(format)}\t{freebie.ToString(format)}");


来源:https://stackoverflow.com/questions/39772055/insert-dynamic-number-format-into-interpolated-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!