c#十进制到字符串的货币
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10437416/
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# Decimal to string for currency
提问by Tom Gullen
To display a currency we do:
要显示货币,我们执行以下操作:
ToString("0.##")
For value 5.00the output is:
对于值5.00,输出为:
5
For value 5.98the output is:
对于值5.98,输出为:
5.98
For value 5.90the output is:
对于值5.90,输出为:
5.9
I need the third case to come out with 2 decimal points, eg:
我需要第三种情况出现 2 个小数点,例如:
5.90
How can I do this without it affecting the other results?
如何在不影响其他结果的情况下执行此操作?
采纳答案by Zachary
I know this doesn't give you a format that fixes the problem, but it's a simple solution to work around it.
我知道这不会为您提供解决问题的格式,但这是解决该问题的简单解决方案。
(5.00).ToString("0.00").Replace(".00",""); // returns 5
(5.90).ToString("0.00").Replace(".00", ""); // returns 5.90
(5.99).ToString("0.00").Replace(".00", ""); // returns 5.99
回答by Jonathan Wood
Try:
尝试:
s.ToString("#,##0.00")
Or just:
要不就:
s.ToString("C")
I know of no built-in way to expand out all two decimal places only when both are not zero. Would probably just use an ifstatement for that.
我知道只有当两个小数位都不为零时,没有内置的方法可以扩展所有两个小数位。可能只是if为此使用一个声明。
int len = s.Length;
if (s[len - 2] == '0' && s[len - 1] == '0')
s = s.Left(len - 3);
回答by ahaliav fox
#means if there is no number leave it empty 0 means put a 0 if there is no number
#表示如果没有数字,则将其留空 0 表示如果没有数字,则输入 0
ToString("0.00")
ToString("0.00")
回答by Clark
You could use an extension method, something like this:
您可以使用扩展方法,如下所示:
public static string ToCurrencyString(this decimal d)
{
decimal t = Decimal.Truncate(d);
return d.Equals(t) ? d.ToString("0.##") : d.ToString("#, ##0.00")
}
回答by gcoleman0828
Not sure if I'm missing something, but can't you just do this:
不确定我是否遗漏了什么,但你不能这样做:
decimal moneyvalue = 1921.39m;
string html = String.Format("Order Total: {0:C}", moneyvalue);
Console.WriteLine(html);
回答by Marc Cals
Just use myDecimal.ToString("N"),
只需使用myDecimal.ToString("N"),
With "N" parameter will transform decimal to string, and the number of decimals to show will be defined by your SO settings.
使用“N”参数会将十进制转换为字符串,并且显示的小数位数将由您的 SO 设置定义。

