我有一些由集合返回的字段
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也会四舍五入其他值。
当前回答
一个非常低级的方法,但我相信这将是最高效的方法,只使用快速整数计算(没有缓慢的字符串解析和区域性敏感的方法):
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);
}
其他回答
一个非常低级的方法,但我相信这将是最高效的方法,只使用快速整数计算(没有缓慢的字符串解析和区域性敏感的方法):
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);
}
这是我写的一个扩展方法,如果它是最后一个字符(在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;
}
}
其他答案:
在WPF应用程序中使用XAML你可以使用
{Binding yourDecimal, StringFormat='#,0.00#######################'}
上面的答案将在某些情况下保留0,因此您仍然可以返回2.00
{Binding yourDecimal, StringFormat='#,0.#########################'}
如果要删除所有后面的零,请相应地进行调整。
像这样试试
string s = "2.4200";
s = s.TrimStart("0").TrimEnd("0", ".");
然后把它转换成浮点数
取决于你的数字代表什么,以及你想如何管理这些值:它是一种货币,你需要舍入还是截断,你只需要这个舍入来显示吗?
如果用于显示,则考虑格式化数字为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"];