【问题标题】:Insert dynamic number format into interpolated string将动态数字格式插入内插字符串
【发布时间】:2016-09-29 13:44:05
【问题描述】:

C# 6.0 带来了这个由$ 指示的漂亮的新格式化操作

而不是这样做

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

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

你可以这样做

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

但是数字格式呢?如果我有这个怎么办:

Decimal price = 9999.95m;
Decimal freebie = 0;

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

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

我试过了:

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

还有这个:

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

还有这个:

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

但它们要么甚至没有编译,要么没有带来预期的结果。

有什么想法吗?

编辑 Howwie 的answer 似乎是去这里的合理方式:

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

【问题讨论】:

  • 你不能那样做,基本上。您必须明确致电string.Format
  • 这与 C# 6.0 无关。这就像在问为什么你不能在以前的版本中做{0:{1}}
  • @Sinatr:我不认为这是重复的。这表明 要格式化的数据 是动态的,而这只是关于格式说明符是动态的。
  • 你可以改为Console.WriteLine($"{price.ToString(format)}\t{freebie.ToString(format)}");

标签: c# string-interpolation


【解决方案1】:

Howwie 的 answer 似乎是去这里的合理方式:

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

【讨论】:

    猜你喜欢
    • 2011-10-19
    • 2022-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多