How do I format a C# decimal to remove extra following 0's?

87,610

Solution 1

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.

Solution 2

string s = d.ToString("0.#############################");

Solution 3

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...

Solution 4

You can specify the format string like this:

String.Format("{0:0.000}", x);

Solution 5

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);
}
Share:
87,610
Scott Stafford
Author by

Scott Stafford

I want what everybody wants. A job where I can change the world modestly for the better, that makes me enough money so I can have everything I want and not so much that my kids want to kill me for the inheritance, and that gives me enough fame to stroke my ego yet I can still dine out in peace.

Updated on July 09, 2022

Comments