Bent Rasmussen
Bent Rasmussen

Reputation: 5702

Normalize a System.Decimal - strip trailing zeros

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 question is decimalValue.ToString() 100% conformant to xs:decimal?

Upvotes: 5

Views: 5102

Answers (4)

orad
orad

Reputation: 16056

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.

Upvotes: 0

Bent Rasmussen
Bent Rasmussen

Reputation: 5702

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.

Upvotes: 1

John Oxley
John Oxley

Reputation: 14990

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

Upvotes: 2

Jonathan Dickinson
Jonathan Dickinson

Reputation: 9218

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);
}

Upvotes: 1

Related Questions