1

I am trying to remove last zero of a decimal value search a lot for this but all answers in web and stack overflow removing all zeros. My aim to display some zeros in last.

Sample
50.00000000
50.01000000
50.01010000
50.01011000
50.01010100

expected 
    50.00
    50.01
    50.0101
    50.01011
    50.010101

I dont lnow how to do it in c#.

I was tried many things like .ToString("G29"); and other answers available but its all giving me like

50.00
50.01
50.01
50.01
50.01

Please Help..

Magnus
  • 45,362
  • 8
  • 80
  • 118
Imran Ali Khan
  • 8,469
  • 16
  • 52
  • 77

4 Answers4

4

Try this:

decimal num = 50.00m;
decimal num2 = 50.01010100m;
Console.WriteLine(num.ToString("0.00#########"));
Console.WriteLine(num2.ToString("0.00#########"));

Output:

50.00
50.010101

(Like suggested in comments by "Alex" and "Erno de Weerd")

MatSnow
  • 7,357
  • 3
  • 19
  • 31
3

You could use TrimEnd to remove the last zeros like this:

decimal num = 50.01011000m;

if (num % 1 == 0)
{
    return num.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture);
}       
string str = num.ToString().TrimEnd('0');

Console.WriteLine(str);

output:

50,01011

You could also pack it into an extension method:

public static class Extensions
{
    public static string ToTrimmendString(this decimal num)
    {
        if (num % 1 == 0)
        {
            return num.ToString("0.00", System.Globalization.CultureInfo.InvariantCulture);
        }
        return num.ToString().TrimEnd('0');
    }
}

and call it like this:

Console.WriteLine(num.ToTrimmendString());
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
0

You can try

    double num = 50.010110000;
    Console.WriteLine(num.ToString("0.0000", CultureInfo.InvariantCulture) );

Please see this for more info https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings#SpecifierPt`

Soumen Mukherjee
  • 2,953
  • 3
  • 22
  • 34
0

you can try something like this

public decimal removeTrailingZeros(decimal val)
{
    return val % 1 == 0 ? Math.Round(val, 2) : val / 1.0000000000000000000000000000000000m;
}

test input

50.00000000m, 50.01000000m, 50.01010000m, 50.01011000m, 50.01010100m,

output

50.00 50.01 50.0101 50.01011 50.010101

styx
  • 1,852
  • 1
  • 11
  • 22