C#:格式化价格值字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1142994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C#: Formatting Price value string
提问by Shyju
in C#,I have a double variable price with value 10215.24. I want to show the price with comma after some digits. My expected output is 10,215.24
在 C# 中,我有一个值为 10215.24 的双变量价格。我想在一些数字后用逗号显示价格。我的预期输出是 10,215.24
采纳答案by Frederik Gheysels
myPrice.ToString("N2");
depending on what you want, you may also wish to display the currency symbol:
根据您的需要,您可能还希望显示货币符号:
myPrice.ToString("C2");
(The number after the C or N indicates how many decimals should be used). (C formats the number as a currency string, which includes a currency symbol)
(C 或 N 后面的数字表示应该使用多少位小数)。(C 将数字格式化为货币字符串,其中包括货币符号)
To be completely politically correct, you can also specify the CultureInfo that should be used.
为了在政治上完全正确,您还可以指定应该使用的 CultureInfo。
回答by Eric Petroelje
I think this should do it:
我认为应该这样做:
String.Format("{0:C}", doubleVar);
If you don't want the currency symbol, then just do this:
如果您不想要货币符号,请执行以下操作:
String.Format("{0:N2}", doubleVar);
回答by Joel Coehoorn
Look into format strings, specifically "C" or "N".
查看格式字符串,特别是“C”或“N”。
double price = 1234.25;
string FormattedPrice = price.ToString("N"); // 1,234.25
回答by Steven Sudit
As a side note, I would recommend looking into the Decimal type for currency. It avoids the rounding errors that plague floats, but unlike Integer, it can have digits after the decimal point.
作为旁注,我建议查看货币的 Decimal 类型。它避免了困扰浮点数的舍入错误,但与 Integer 不同的是,它可以在小数点后有数字。
回答by Thunder
This might help
这可能有帮助
String.Format("{#,##0.00}", 1243.50); // Outputs “1,243.50″
String.Format("{0:$#,##0.00;($#,##0.00);Zero}", 1243.50); // Outputs “,243.50″
String.Format("{0:$#,##0.00;($#,##0.00);Zero}", -1243.50); // Outputs “(,243.50)″
String.Format("{0:$#,##0.00;($#,##0.00);Zero}", 0); // Outputs “Zero″
回答by WonderWorker
The one you want is "N2".
你想要的是“N2”。
Here is an example:
下面是一个例子:
double dPrice = 29.999988887777666655554444333322221111;
string sPrice = "£" + dPrice.ToString("N2");
You might even like this:
你甚至可能喜欢这个:
string sPrice = "";
if(dPrice < 1)
{
sPrice = ((int)(dPrice * 100)) + "p";
} else
{
sPrice = "£" + dPrice.ToString("N2");
}
which condenses nicely to this:
这很好地浓缩为:
string sPrice = dPrice < 1 ? ((int)(dPrice * 100)).ToString("N0") + "p" : "£" + dPrice.ToString("N2");
Further reading at msdn.microsoft.com/en-us/library/fht0f5be.aspxfor various other types of formatting
在msdn.microsoft.com/en-us/library/fht0f5be.aspx进一步阅读各种其他类型的格式