使用“,”和“.”定位小数时出错

Error localising decimals with "," and "."

我希望价格是小数点并且小数点符号是本地化的。根据文化,小数可以使用 ,..

现在我正在这样做:

subItem.price.ToString("#.#", CultureInfo.InvariantCulture);

但是如果价格是0(没有小数点),结果就是"",这会让我的系统崩溃。

是否有比 "#.#" 更好的模式可以更好地处理 0

使用 "0" custom format specifier 怎么样?

Console.WriteLine((0).ToString("0.0", CultureInfo.InvariantCulture));

打印

0.0

您的代码 returns 为空字符串,因为来自 The "#" custom format specifier

Replaces the "#" symbol with the corresponding digit if one is present; otherwise, no digit appears in the result string. Note that this specifier never displays a zero that is not a significant digit, even if zero is the only digit in the string. It will display zero only if it is a significant digit in the number that is being displayed.

顺便说一句,你的标题和你的问题说的是不同的东西。您的问题与格式化值时使用的小数点分隔符无关。这就是为什么在格式化 0 值时得到空字符串的原因。

尝试0.#。如果值为 0.0

,将显示 0

可能尝试使用:

subItem.price.ToString("{0:C}", CultureInfo.InvariantCulture);

它将您的字符串格式化为货币。