50

I want to format a string as a decimal, but the decimal contains some following zeros after the decimal. How do I format it such that those meaningless 0's disappear?

string.Format("{0}", 1100M);
string.Format("{0}", 1100.1M);
string.Format("{0}", 1100.100M);
string.Format("{0}", 1100.1000M);

displays:

1100
1100.1
1100.100
1100.1000

but I want it to be:

1100
1100.1
1100.1
1100.1

For reference, here are other questions that are essentially duplicates of this, that I've found thanks to answers given here:

Community
  • 1
  • 1
Scott Stafford
  • 43,764
  • 28
  • 129
  • 177

11 Answers11

85

You can use ToString() with the General ("G") Format Specifier to achieve the desired result. Trailing zeros are truncated when using this format string with a precision specified. In order to prevent rounding in any situations, you will need to set the precision to the maximum allowed for decimals (29).

The line of code to produce what you want is number.ToString("G29"), where number is your original decimal.

Be aware that any numbers smaller than 0.0001 will be converted to scientific notation. More details on how this formatter works can be found at the reference link above.

Herohtar
  • 5,347
  • 4
  • 31
  • 41
  • 5
    I think this is the best solution to the question. – Wegged May 13 '11 at 17:17
  • 2
    Concur -- switched answer. Thanks, @Herohtar. – Scott Stafford Oct 05 '12 at 18:45
  • 2
    WARNING: Watch out for values like 0.000001. G29 format will present them in the shortest possible way so it will switch to the exponential notation. string.Format("{0:G29}", decimal.Parse("0.00000001",System.Globalization.CultureInfo.GetCultureInfo("en-U‌​S"))) will give "1E-08" as the result. Credit goes to Konrad here: http://stackoverflow.com/questions/4525854/remove-trailing-zeros/4525983#4525983 – Doug S Nov 07 '12 at 22:26
  • @DougS: It seems that it switches to scientific notation for numbers less than 0.0001 (eg, 0.0001 remains the same, but 0.00009 will be 9E-05) That seems unlikely to be a problem in most cases of wanting to truncate zeros, but a good thing to know nonetheless. – Herohtar Nov 09 '12 at 15:39
  • @Herohtar: I wouldn't say it's "unlikely" at all. In fact, it's very likely if someone is working with decimals less than 1. For instance, I store decimal(12,10) in my database, and G29 would fail on 0.0000010000 or anything like it. – Doug S Nov 10 '12 at 17:19
  • The answer has been updated with a correct link and current information. – Herohtar Apr 07 '14 at 20:08
  • I still get the trailing zeros with the "G" formatting. – Jonathan Wood Nov 19 '14 at 01:41
  • 1
    The G29 is not necessary. "G0"=="G29" for decimal – statler Sep 30 '17 at 02:40
  • What if I don't want it to use scientific notation? – SuperJMN May 23 '19 at 08:58
23
string s = d.ToString("0.#############################");
Jason dinAlt
  • 291
  • 3
  • 5
4

Unlike what everybody suggest to use a G format specifier I would suggest the following to preserve both thousand separator and decimal point while removing extra trailing zeros:

{0:#,#.##}

The result of this format is much better than G in most cases:

String.Format("{0:#,#.##}",25/2.4);
10.42

String.Format("{0:#,#.##}",1000000);
1,000,000

String.Format("{0:#,#.##}",1000000.3600000);
1,000,000.36

And the G specifier can't really handle all the possible combinations:

String.Format("{0:G29}",25/2.4);
10.416666666666668

String.Format("{0:G2}",25/2.4);
10

String.Format("{0:G29}",1000000.3600000);
1000000.36

String.Format("{0:G2}",1000000.3600000);
1E+06
Mohsen Afshin
  • 13,273
  • 10
  • 65
  • 90
4

You can specify the format string like this:

String.Format("{0:0.000}", x);
driis
  • 161,458
  • 45
  • 265
  • 341
  • 2
    But I don't know that it's got three decimals on the end, I meant that only as an example. I'll make the question clearer. – Scott Stafford Jan 24 '11 at 20:22
4

They're not necessarily meaningless - they indicate the precision during calculation. Decimals maintain their precision level, rather than being normalized.

I have some code in this answer which will return a normalized value - you could use that, and then format the result. For example:

using System;
using System.Numerics;

class Test
{
    static void Display(decimal d)
    {
        d = d.Normalize(); // Using extension method from other post
        Console.WriteLine(d);
    }

    static void Main(string[] args)
    {
        Display(123.4567890000m); // Prints 123.456789
        Display(123.100m);        // Prints 123.1
        Display(123.000m);        // Prints 123
        Display(123.4567891234m); // Prints 123.4567891234
    }
}

I suspect that most of the format string approaches will fail. I would guess that a format string of "0." and then 28 # characters would work, but it would be very ugly...

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    It looks like your solution is for .Net 4.0 only. – Gabe Jan 24 '11 at 20:34
  • @Gabe: Unless you use a 3rd party BigInteger implementation, yes. It's also pretty inefficient. On the other hand, it has the advantage of working :) – Jon Skeet Jan 24 '11 at 20:34
3

How about:

string FormatDecimal(decimal d)
{
    const char point = System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator[0];
    string s = d.ToString();
    // if there's no decimal point, there's nothing to trim
    if (!s.Contains(point) == -1)
        return s;
    // trim any trailing 0s, followed by the decimal point if necessary
    return s.TrimEnd('0').TrimEnd(point);
}
Gabe
  • 84,912
  • 12
  • 139
  • 238
  • Use System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator instead of '.'? – Yoshi Jan 24 '11 at 21:26
2

Quite a few answers already. I often refer to this cheat sheet: http://blog.stevex.net/string-formatting-in-csharp/

Baz Hughes
  • 21
  • 1
2

Somewhat hackish, but this should work:

decimal a = 100.00M;
string strNumber = string.Format("{0}", a);
Console.WriteLine(strNumber.Contains('.') ? strNumber.TrimEnd('0').TrimEnd('.') : strNumber);
Davy8
  • 30,868
  • 25
  • 115
  • 173
1
String.Format("{0:0.##}", 123.0); // "123"
Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
John K.
  • 5,426
  • 1
  • 21
  • 20
1

I believe you want to do:

var s = String.Format("{0:#####.###}");
AlG
  • 14,697
  • 4
  • 41
  • 54
-3
double a = 1100.00
double  b =1100.1
double  c = 1100.100
double  d =1100.1000

Remove last zero after point


string stra = a.toString("0.00").TrimEnd('0').TrimEnd('.');
string strb = b.toString("0.00").TrimEnd('0').TrimEnd('.');
string strc = c.toString("0.00").TrimEnd('0').TrimEnd('.');
string strd = d.toString("0.00").TrimEnd('0').TrimEnd('.');

Output

1100
1100.1
1100.1
1100.1