我有一些由集合返回的字段
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也会四舍五入其他值。
当前回答
string.Format("{0:G29}", decimal.Parse("2.00"))
string.Format("{0:G29}", decimal.Parse(Your_Variable))
其他回答
string.Format("{0:G29}", decimal.Parse("2.00"))
string.Format("{0:G29}", decimal.Parse(Your_Variable))
一个非常低级的方法,但我相信这将是最高效的方法,只使用快速整数计算(没有缓慢的字符串解析和区域性敏感的方法):
public static decimal Normalize(this decimal d)
{
int[] bits = decimal.GetBits(d);
int sign = bits[3] & (1 << 31);
int exp = (bits[3] >> 16) & 0x1f;
uint a = (uint)bits[2]; // Top bits
uint b = (uint)bits[1]; // Middle bits
uint c = (uint)bits[0]; // Bottom bits
while (exp > 0 && ((a % 5) * 6 + (b % 5) * 6 + c) % 10 == 0)
{
uint r;
a = DivideBy10((uint)0, a, out r);
b = DivideBy10(r, b, out r);
c = DivideBy10(r, c, out r);
exp--;
}
bits[0] = (int)c;
bits[1] = (int)b;
bits[2] = (int)a;
bits[3] = (exp << 16) | sign;
return new decimal(bits);
}
private static uint DivideBy10(uint highBits, uint lowBits, out uint remainder)
{
ulong total = highBits;
total <<= 32;
total = total | (ulong)lowBits;
remainder = (uint)(total % 10L);
return (uint)(total / 10L);
}
像这样试试
string s = "2.4200";
s = s.TrimStart("0").TrimEnd("0", ".");
然后把它转换成浮点数
我遇到了同样的问题,但在我无法控制输出到字符串的情况下,这是由库处理的。在详细了解了Decimal类型的实现(参见http://msdn.microsoft.com/en-us/library/system.decimal.getbits.aspx)后, 我想出了一个巧妙的技巧(这里是一个扩展方法):
public static decimal Normalize(this decimal value)
{
return value/1.000000000000000000000000000000000m;
}
小数点的指数部分被缩减为所需的部分。对输出小数调用ToString()将写入不带任何0的数字。如。
1.200m.Normalize().ToString();
这是可行的:
decimal source = 2.4200m;
string output = ((double)source).ToString();
或者如果你的初始值是string:
string source = "2.4200";
string output = double.Parse(source).ToString();
请注意这条评论。