user2818430
user2818430

Reputation: 6029

Format decimal number with custom amount of digits after comma

I have this custom extension that should format a decimal number with a custom amount of digits after comma.

public static decimal FormatDecimal(this decimal value, int decimalSeparator = 2)
{
    decimal returnValue = Math.Round(value, decimalSeparator, MidpointRounding.AwayFromZero);
    return returnValue;
}

The problem is that doesn't work as expected.

If I do like this:

decimal number = 12345;

and then:

decimal formatedNumber = number.FormatDecimal(2);

the result should be:

12345.00

instead the result is:

12345

What I am doing wrong?

Upvotes: 1

Views: 3327

Answers (4)

Paolo Costa
Paolo Costa

Reputation: 1989

Here's the extension function working

    public static string FormatDecimal(this decimal value, int decimalSeparator = 2)
    {
        return  value.ToString(string.Format("0.{0}", new string('0', decimalSeparator)));
    }

Upvotes: 1

Y2theZ
Y2theZ

Reputation: 10402

You should specify the formatting when you display the string.

What you need is to do the following, when you convert to string:

String.Format("{0:0.00}", formatedNumber);

Refer to This article for more details:

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98740

I think the right way is to using The "0" custom format specifier;

Replaces the zero with the corresponding digit if one is present; otherwise, zero appears in the result string.

For example;

decimal d = 12345;
Console.WriteLine(d.ToString("#.00")); // 12345.00

Upvotes: 1

Brian Snow
Brian Snow

Reputation: 1143

You're probably looking to format the string representation of your decimal instead. Try this:

decimal myNumber = 12345.67m;
string formattedNumber = myNumber.ToString("N3");
Console.WriteLine(formattedNumber); // Prints "12345.670"

See here for more information: https://msdn.microsoft.com/en-us/library/dwhawy9k%28v=vs.110%29.aspx

From MSDN:

Standard numeric format strings are used to format common numeric types. A standard numeric format string takes the form Axx, where:

A is a single alphabetic character called the format specifier. Any numeric format string that contains more than one alphabetic character, including white space, is interpreted as a custom numeric format string. For more information, see Custom Numeric Format Strings.

xx is an optional integer called the precision specifier. The precision specifier ranges from 0 to 99 and affects the number of digits in the result. Note that the precision specifier controls the number of digits in the string representation of a number. It does not round the number itself. To perform a rounding operation, use the Math.Ceiling, Math.Floor, or Math.Round method.

When precision specifier controls the number of fractional digits in the result string, the result strings reflect numbers that are rounded away from zero (that is, using MidpointRounding.AwayFromZero).

Upvotes: 0

Related Questions