Add comma thousand separator to decimal (.net)

I have a decimal number, say 1234.500.

I want to get it to display 1,234.4

Im currently converting it to a double to remove the trailing '0's.

string.Format("{0:0,0}",1234.500) removes the decimal place, and other formatting options seem to use two decimal places regardless.

Can anyone offer insight?


You should use a custom formatting like #,##0.00

string s = string.Format("{0:#,##0.00}", xx);

Will produce 1,234.50 when xx = 1234.5M
forget about converting to double , that won't really help.


Are you aware that .NET has built-in support for correctly formatting numbers according the the regional settings of each user of your application? It might be better to leverage the user's own regional settings (the .NET framework knows all the right settings already).

However, if you want to fix your application to format numbers in a particular regional setting, you can still leveage a particular locale of your choice and force .NET to use that as the basis of all formatting (not just numbers):

using System.Globalization;
using System.Threading;
...
CultureInfo us = new CultureInfo("en-US");

and then

Thread.CurrentThread.CurrentUICulture = us;

or just

Console.WriteLine(d.ToString("c", us));

You should be aware that the use of commas as a thousands separator is appropriate for UK and USA but it is not how thousands should be displayed in other countries

"one thousand and twenty-five is displayed as 1,025 in the United States and 1.025 in Germany. In Sweden, the thousands separator is a space"

MSDN has dedicated section devoted to this topic which they call 'Globalization' (ie that's a good search term if ever you need to hunt down more detail). That page describes how the use of the pound sign works as a digit placeholder for removing the trailing zeros (as suggested by Henk Holterman in a previous comment).

See also Custom Numeric Format Strings.


另一种选择:

decimal d = 1234.56m;
string s = d.ToString("N");    // 1,234.56
链接地址: http://www.djcxy.com/p/50536.html

上一篇: 使用String.Format为数字和。添加逗号

下一篇: 将逗号分隔符千位分隔符(.net)