tags:

views:

341

answers:

2

I noticed that .NET has some funky/unintuitive behavior when it comes to decimals and trailing zeros.

0m == 0.000m //true
0.1m == 0.1000m //true

but

(0m).ToString() == (0.000m).ToString() //false
(0.1m).ToString() == (0.1000m).ToString() //false

I know about necessity to comply to the ECMA CLI standard. However I would like to know if there is built-in way to truncate the trailing zeros for a decimal value without going through string representation (.ToString("G29") and parse back trick would work, but is neither fast nor elegant solution)?

Any ideas? Thanks a lot.

+3  A: 

Use a format string to specify the output of ToString():

(0.1m).ToString("0.#") -> "0.1"
(0.10000m).ToString("0.#") -> "0.1"

Use a "0" in the format to specify a digit or a non-significate 0, use "#" to specify a significant digit or suppress a a non-significate 0.

Edit: I assuming here that you are worried about the visual (string) representation of the number - if not, I will remove my answer.

Ray
I don't care that much about visual representation. The problem is that when I pass those values to the JScript engine, it gets messed up for some reason by the 1.0000m type values. Thx for the answer any nonetheless. P.S. 0.10000m.ToString("G29") works for any number of significant digits.
Konrad
+1  A: 

I don't like it much, but it works (for some range of values, at least)...

    static decimal Normalize(decimal value)
    {
        long div = 1;
        while(value - decimal.Truncate(value) != 0)
        {
            div *= 10;
            value *= 10;
        }
        if(div != 1) {
            value = (decimal)(long)value / div;
        }
        return value;
    }
Marc Gravell
It works for most cases. Unfortunately it doesn't work for 0.00000m type of values. It would need another 'if' to check for decimal zero and this would make it even more messy.
Konrad