我有一个十进制值,它在.后面有可变位数,例如:
0.0030
0.0310
0.0001
1.1200如何编写一个动态函数来删除小数点末尾的0?
发布于 2010-01-21 21:31:59
string.Format("{0:0.#####}", 0.0030)或
var money=1.3000m;
money.ToString("0.#####");对于将来的参考,我推荐John Sheehan的.NET Format String Quick Reference。
发布于 2011-11-03 00:01:54
您还可以修改小数本身,以便任何ToString()都能提供您想要的结果(在我的答案here中有更多详细信息):
public static decimal Normalize(decimal value)
{
return value/1.000000000000000000000000000000000m;
}发布于 2010-01-21 21:36:37
decimal value = 0.0030m;
value.ToString(“G29″);编辑:G格式化程序可以工作,唯一的问题是,如果原始小数中有太多有效数字,它会跳转到科学记数法。不是很理想。
请参阅此处的“通用("G")格式说明符”文档:http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#GFormatString
我在吃午饭,所以我做了个小测试:
decimal d1 = 0.000100m;
decimal d2 = 0.001000000000000000000000m;
decimal d3 = 0.000000000000001000000000m;
Console.WriteLine(Environment.NewLine + "input decimal: 0.000100m");
Console.WriteLine("G " + d1.ToString("G"));
Console.WriteLine("G29 " + d1.ToString("G29"));
Console.WriteLine("0.####### " + d1.ToString("0.#######"));
Console.WriteLine(Environment.NewLine + "input decimal: 0.001000000000000000000000m");
Console.WriteLine("G " + d2.ToString("G"));
Console.WriteLine("G29 " + d2.ToString("G29"));
Console.WriteLine("0.####### " + d2.ToString("0.#######"));
Console.WriteLine(Environment.NewLine + "input decimal: 0.000000000000001000000000m");
Console.WriteLine("G " + d3.ToString("G"));
Console.WriteLine("G29 " + d3.ToString("G29"));
Console.WriteLine("0.####### " + d3.ToString("0.#######"));输出:
input decimal: 0.000100m
G 0.000100
G29 0.0001
0.####### 0.0001
input decimal: 0.001000000000000000000000m
G 0.001000000000000000000000
G29 0.001
0.####### 0.001
input decimal: 0.000000000000001000000000m
G 0.000000000000001000000000
G29 1E-15
0.####### 0https://stackoverflow.com/questions/2109494
复制相似问题