Steven Lemmens
Steven Lemmens

Reputation: 1491

Format a Decimal with four digits, except when those digits are zeroes

We have a specific formatting issue we would like to address in the most efficient way possible.

We have to format a Decimal to four digits after the decimal point EXCEPT when there are no decimals, because in that case the decimal should be formatted to two digits after the decimal point

I'll give a few examples to explain:

1.234 should be printed as 1.234 (all digits) while 1.000 should be printed as 1.00 (limited to two digits) and 1.500 should be printed as 1.50 (limited to two digits)

In other words: we want to remove all unneccessary zeroes after the decimal point, but make sure that there are always two digits remaining after the comma.

I'm guessing there is no easy way to do this already supplied in .NET ? If so, I was thinking I could use the .ToString() function to turn it into a string and parse everything after the decimal point? Or does anyone have any more efficient ideas?

Upvotes: 1

Views: 2995

Answers (2)

mm8
mm8

Reputation: 169300

Calling the decimal.ToString() method with the following format specifier should give you an output with between 2 and 4 decimals:

decimal d = 1.234m;
string output = d.ToString("0.00##");

For more information about numeric format specifiers, please refer to MSDN.

Standard Numeric Format Strings: https://msdn.microsoft.com/en-us/library/0b22a4x2(v=vs.110).aspx

Custom Numeric Format Strings: https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings

Upvotes: 5

Coskun Ozogul
Coskun Ozogul

Reputation: 2487

What about this ?

    string SetDecimals(decimal val)
    {
        var decimalStr = val.ToString().Split(new string[] { System.Threading.Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator }, StringSplitOptions.None)[1];
        if (decimalStr.Length == 4 && !decimalStr.EndsWith("00"))
            return string.Format("{0:N4}", val);
        else if(decimalStr.Length == 3 && !decimalStr.EndsWith("0"))
            return string.Format("{0:N3}", val);
        else
            return string.Format("{0:N2}", val);
    }

Upvotes: 0

Related Questions