C# 如何将双精度格式设置为四舍五入到最接近的美元的货币?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/890100/
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
How do I format a double to currency rounded to the nearest dollar?
提问by spilliton
Right now I have
现在我有
double numba = 5212.6312
String.Format("{0:C}", Convert.ToInt32(numba) )
This will give me
这会给我
,213.00
but I don't want the ".00".
但我不想要“.00”。
I know I can just drop the last three characters of the string every time to achieve the effect, but seems like there should be an easier way.
我知道我每次都可以删除字符串的最后三个字符来达到效果,但似乎应该有更简单的方法。
采纳答案by Marc Gravell
First - don't keep currency in a double
- use a decimal
instead. Every time. Then use "C0" as the format specifier:
首先 - 不要将货币放在 a 中double
- 使用 adecimal
代替。每次。然后使用“C0”作为格式说明符:
decimal numba = 5212.6312M;
string s = numba.ToString("C0");
回答by RedFilter
Console.WriteLine(numba.ToString("C0"));
回答by Noldorin
回答by Pejvan
I think the right way to achieve your goal is with this:
我认为实现目标的正确方法是:
Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyDecimalDigits = 0;
and only then you should do the Format call:
只有这样你才应该做 Format 调用:
String.Format("{0:C0}", numba)
回答by Rodrigo Reis
simple: numba.ToString("C2")
简单的: numba.ToString("C2")
more @ http://msdn.microsoft.com/pt-br/library/dwhawy9k(v=vs.110).aspx#CFormatString
更多 @ http://msdn.microsoft.com/pt-br/library/dwhawy9k(v=vs.110).aspx#CFormatString
回答by Bhanu Pratap
decimal value = 0.00M;
value = Convert.ToDecimal(12345.12345);
Console.WriteLine(".ToString(\"C\") Formates With Currency $ Sign");
Console.WriteLine(value.ToString("C"));
//OutPut : 345.12
Console.WriteLine(value.ToString("C1"));
//OutPut : 345.1
Console.WriteLine(value.ToString("C2"));
//OutPut : 345.12
Console.WriteLine(value.ToString("C3"));
//OutPut : 345.123
Console.WriteLine(value.ToString("C4"));
//OutPut : 345.1235
Console.WriteLine(value.ToString("C5"));
//OutPut : 345.12345
Console.WriteLine(value.ToString("C6"));
//OutPut : 345.123450
click to see Console Out Put screen
Hope this may Help you...
希望这可以帮助你...
Thanks. :)
谢谢。:)