我有一些由集合返回的字段

2.4200
2.0044
2.0000

我想要这样的结果

2.42
2.0044
2

我试过用String。格式,但它返回2.0000,并将其设置为N0也会四舍五入其他值。


当前回答

这很简单。

decimal decNumber = Convert.ToDecimal(value);
        return decNumber.ToString("0.####");

测试。

欢呼:)

其他回答

我从http://dobrzanski.net/2009/05/14/c-decimaltostring-and-how-to-get-rid-of-trailing-zeros/上找到了一个优雅的解决方案

基本上

decimal v=2.4200M;

v.ToString("#.######"); // Will return 2.42. The number of # is how many decimal digits you support.

这是可行的:

decimal source = 2.4200m;
string output = ((double)source).ToString();

或者如果你的初始值是string:

string source = "2.4200";
string output = double.Parse(source).ToString();

请注意这条评论。

这个怎么样:

public static string TrimEnd(this decimal d)
    {
        string str = d.ToString();
        if (str.IndexOf(".") > 0)
        {
            str = System.Text.RegularExpressions.Regex.Replace(str.Trim(), "0+?$", " ");
            str = System.Text.RegularExpressions.Regex.Replace(str.Trim(), "[.]$", " ");
        }
        return str;
    }

取决于你的数字代表什么,以及你想如何管理这些值:它是一种货币,你需要舍入还是截断,你只需要这个舍入来显示吗?

如果用于显示,则考虑格式化数字为x.ToString("")

http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx和

http://msdn.microsoft.com/en-us/library/0c899ak8.aspx

如果只是四舍五入,请使用Math。需要midpointround重载的圆重载

http://msdn.microsoft.com/en-us/library/ms131274.aspx)

如果你从数据库中获取值,考虑转换而不是转换: double value = (decimal)myRecord["columnName"];

你可以设置为:

decimal decNumber = 23.45600000m;
Console.WriteLine(decNumber.ToString("0.##"));