Search code examples
c#decimalstrip

C# equivalent of BigDecimal.stripTrailingZeros()


In Java you can use BigDecimal.stripTrailingZeros() to remove any extra zeros at the end.

I've read a few questions on here about how to strip trailing zeros from a decimal in C# but none of them seem to offer correct solutions.

This question for example the answer of doing ToString("G") doesn't always work.

Ideally I would like a function that does decimal -> decimal with the new decimal having the least scale possible without losing any info or removing any trailing zeros.

Is there any way to do this easily? Or would it involve fiddling around with decimal.GetBits()?

EDIT: Should also add I have i18n to worry about so doing string manipulation on the result isn't ideal because of differences in decimal separators.


Solution

  • Here is what i have come up with (Crazy code but works smoothly)

    private decimal Normalize(decimal d)
    {
        string[] tmp = d.ToString().Split('.');
        string val = tmp[0];    
        string fraction = null;
        decimal result;
        if(tmp.Length > 1) fraction = tmp[1];
        if(fraction != null && Getleast(fraction) > 0) 
        {
            decimal.TryParse(val.ToString() + "." + fraction.TrimEnd('0').ToString(),out result);
        }
        else
        {
            return decimal.Parse(val);
        }
        return result;
    }
    
    private decimal Getleast(string str)
    {
        decimal res;
        decimal.TryParse(str.TrimEnd('0'),out res);// It returns 0 even if we pass null or empty string
        return res;
    }
    

    Here are sample Input:

    Console.WriteLine(Normalize(0.00M));
    Console.WriteLine(Normalize(0.10M));
    Console.WriteLine(Normalize(0001.00M));
    Console.WriteLine(Normalize(1000.01M));
    Console.WriteLine(Normalize(1.00001230M));
    Console.WriteLine(Normalize(0031.200M));        
    Console.WriteLine(Normalize(0.0004000M));
    Console.WriteLine(Normalize(123));
    

    And respective output:

    0
    0.1
    1
    1000.01
    1.0000123
    31.2
    0.0004
    123