我有一些由集合返回的字段
2.4200
2.0044
2.0000
我想要这样的结果
2.42
2.0044
2
我试过用String。格式,但它返回2.0000,并将其设置为N0也会四舍五入其他值。
我有一些由集合返回的字段
2.4200
2.0044
2.0000
我想要这样的结果
2.42
2.0044
2
我试过用String。格式,但它返回2.0000,并将其设置为N0也会四舍五入其他值。
当前回答
取决于你的数字代表什么,以及你想如何管理这些值:它是一种货币,你需要舍入还是截断,你只需要这个舍入来显示吗?
如果用于显示,则考虑格式化数字为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"];
其他回答
尝试做更友好的解决方案DecimalToString (https://stackoverflow.com/a/34486763/3852139):
private static decimal Trim(this decimal value)
{
var s = value.ToString(CultureInfo.InvariantCulture);
return s.Contains(CultureInfo.InvariantCulture.NumberFormat.NumberDecimalSeparator)
? Decimal.Parse(s.TrimEnd('0'), CultureInfo.InvariantCulture)
: value;
}
private static decimal? Trim(this decimal? value)
{
return value.HasValue ? (decimal?) value.Value.Trim() : null;
}
private static void Main(string[] args)
{
Console.WriteLine("=>{0}", 1.0000m.Trim());
Console.WriteLine("=>{0}", 1.000000023000m.Trim());
Console.WriteLine("=>{0}", ((decimal?) 1.000000023000m).Trim());
Console.WriteLine("=>{0}", ((decimal?) null).Trim());
}
输出:
=>1
=>1.000000023
=>1.000000023
=>
在我看来,使用自定义数字格式字符串更安全。
decimal d = 0.00000000000010000000000m;
string custom = d.ToString("0.#########################");
// gives: 0,0000000000001
string general = d.ToString("G29");
// gives: 1E-13
这是我写的一个扩展方法,如果它是最后一个字符(在0被删除之后),它也会删除点或逗号:
public static string RemoveZeroTail(this decimal num)
{
var result = num.ToString().TrimEnd(new char[] { '0' });
if (result[result.Length - 1].ToString() == "." || result[result.Length - 1].ToString() == ",")
{
return result.Substring(0, result.Length - 1);
}
else
{
return result;
}
}
试试下面的代码:
string value = "100";
value = value.Contains(".") ? value.TrimStart('0').TrimEnd('0').TrimEnd('.') : value.TrimStart('0');
你可以设置为:
decimal decNumber = 23.45600000m;
Console.WriteLine(decNumber.ToString("0.##"));