C # equivalent of BigDecimal.stripTrailingZeros ()

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

I read a few questions here on how to separate zero zeros from a decimal in C #, but none of them offer the right solutions.

This question , for example, the answer to the execution of ToString ("G") does not always work.

Ideally, I need a function that does decimal - decimal with a new decimal number having the smallest scale, without losing information or removing any trailing zeros.

Is there any way to make this easy? Or will it be related to decimal.GetBits()?

EDIT: I must also add that I have i18n to worry that string manipulation by result is not perfect due to differences in decimal separators.

+3
source share
3 answers

Here is what I came up with (Crazy code, but it 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 is an example 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 the corresponding conclusion:

0
0.1
1
1000.01
1.0000123
31.2
0.0004
123
+1
source

How about Decimal.Parse(d.ToString("0.###########################"))?

+2
source

Not the most elegant of solutions, but it should do everything you need.

 private decimal RemoveTrailingZeros(decimal Dec)
    {
        string decString = Dec.ToString();

        if (decString.Contains("."))
        {
            string[] decHalves = decString.Split('.');

            int placeholder = 0, LoopIndex = 0;

            foreach (char chr in decHalves[1])
            {
                LoopIndex++;
                if (chr != '0')
                    placeholder = LoopIndex;
            }

            if (placeholder < decHalves[1].Length)
                decHalves[1] = decHalves[1].Remove(placeholder);

            Dec = decimal.Parse(decHalves[0] + "." + decHalves[1]);
        }

        return Dec;
    }

Fixed version, thanks Shekhar_Pro!

0
source

Source: https://habr.com/ru/post/1793613/


All Articles