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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 08:35:40  来源:igfitidea点击:

How do I format a double to currency rounded to the nearest dollar?

c#formattingroundingcurrency

提问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 decimalinstead. 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

This should do the job:

这应该可以完成这项工作:

String.Format("{0:C0}", Convert.ToInt32(numba))

The number after the Cspecifies the number of decimal places to include.

后面的数字C指定要包含的小数位数。

I suspect you really want to be using the decimaltype for storing such numbers however.

但是,我怀疑您真的想使用该decimal类型来存储此类数字。

回答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 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. :)

谢谢。:)