I've got a pretty compact way of removing trailing zeros in decimal values but I'd prefer a way that doesn't involve string roundtripping as mine currently does. This is my current solution:
var value = 0.010m;
value = decimal.Parse(value.ToString("G29"));
Console.WriteLine(value); // prints 0.01 (not 0.010)
So it works, but do you have an even better way?
Also, as a secondary questio开发者_运维技巧n is decimalValue.ToString() 100% conformant to xs:decimal?
It doesn't really matter how many SF the number is stored as but rather what happens when you output it.
Try
// The number of #'s is the number of decimal places you want to display
Console.WriteLine(value.ToString("0.###############");
// Prints 0.01
To answer your second question, System.XmlConvert.ToString(decimal value)
is 100% conformant to xs:decimal.
This should be slightly faster.
public static decimal StripTrailingZeroes(this decimal value)
{
return decimal.Parse(value.ToString("G29", CultureInfo.InvariantCulture), CultureInfo.InvariantCulture);
}
Here's a new draft idea:
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;
}
}
This might just do it. But it's very rough. Need to test and simplify it.
Casting to double
and back to decimal
should work.
decimal fixDecimal(decimal number) => (decimal)(double)number;
Though, there might be edge cases that I'm not aware of.
精彩评论