我有一些由集合返回的字段
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也会四舍五入其他值。
当前回答
这是可行的:
decimal source = 2.4200m;
string output = ((double)source).ToString();
或者如果你的初始值是string:
string source = "2.4200";
string output = double.Parse(source).ToString();
请注意这条评论。
其他回答
这是可行的:
decimal source = 2.4200m;
string output = ((double)source).ToString();
或者如果你的初始值是string:
string source = "2.4200";
string output = double.Parse(source).ToString();
请注意这条评论。
下面的代码可以用来不使用字符串类型:
int decimalResult = 789.500
while (decimalResult>0 && decimalResult % 10 == 0)
{
decimalResult = decimalResult / 10;
}
return decimalResult;
返回789.5
其他答案:
在WPF应用程序中使用XAML你可以使用
{Binding yourDecimal, StringFormat='#,0.00#######################'}
上面的答案将在某些情况下保留0,因此您仍然可以返回2.00
{Binding yourDecimal, StringFormat='#,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.
这是我写的一个扩展方法,如果它是最后一个字符(在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;
}
}