标准化一个System.Decimal - 条尾随零
我有一个非常紧凑的方式去除十进制值中的尾随零,但我更喜欢一种不涉及字符串往返的方式,就像我现在所做的那样。这是我目前的解决方案:标准化一个System.Decimal - 条尾随零
var value = 0.010m;
value = decimal.Parse(value.ToString("G29"));
Console.WriteLine(value); // prints 0.01 (not 0.010)
所以它的工作,但你有更好的办法吗?
此外,第二个问题是decimalValue.ToString()100%符合xs:decimal?
这里有一个新的想法草案:
public static class DecimalEx
{
public static decimal Fix(this decimal value)
{
var x = value;
var i = 28;
while (i > 0)
{
var t = decimal.Round(x, i);
if (t != x)
return x;
x = t;
i--;
}
return x;
}
}
这可能只是做到这一点。但它很粗糙。需要测试和简化它。
要回答第二个问题,System.XmlConvert.ToString(decimal value)
与xs:decimal是100%一致的。
这个应该稍快。
public static decimal StripTrailingZeroes(this decimal value)
{
return decimal.Parse(value.ToString("G29", CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
}
谢谢,我会用它! :-) –
@Bent - 抱歉,我无法解决原始问题 - 我尝试了解Decimal是如何工作的,它的记录很差,看起来像修改'int [4]'表示法可能会很棘手。我会让这是一个扩展方法,如果它成为一个问题,它会在稍后优化它;很有可能它不是一个很大的perf perf(听起来像是过早的优化)。我已经编辑了我的问题,应该是什么,最快的字符串往返。 –
这只是“我脑海中的碎片”问题:它不应该改变表示形式为字符串去掉尾随的零,所以它让我难堪,但是你很正确,它应该是正确的,这是最重要的。 –
它并不真正的问题多少SF数存储为,但是当你输出它,而会发生什么。
尝试
// The number of #'s is the number of decimal places you want to display
Console.WriteLine(value.ToString("0.###############");
// Prints 0.01
- 当然,我可以重复截断和比较小数点,直到值不再相等。至少(0.010米== 0.01米) –
相关问题:http://stackoverflow.com/questions/3683718/is-there-a-way-to-get-the-significant-figures-of-a-decimal –
最好的办法是用Jon的答案来解答同样的问题:http://stackoverflow.com/questions/4298719/parse-decimal-and-filter-extra-0-on-the-right/4298787#4298787 – Gabe