Specify default format for Decimal.ToString() meth

2019-08-04 15:05发布

问题:

I have an application with a lot of calls to Decimal.ToString(void). The default format is not what is needed. I could change these calls to one of the other Decimal.ToString overloads, but it would be nicer if I didn't have to. So, is there a way to specify a different format for the Decimal.ToString(void) method so that I don't have to modify any of the calls to this method?

Update

As the answer below indicates, it is possible to do what I want, but I should not do so as it is not good programming practice. There are many alternative approaches which involve rewriting the calls; the approach I plan to go with is to store the desired format as a string constant and pass that to the calls:

class Example
{
    const string s_DecimalFormat = "N2";

    private decimal myDecimal1 = 12.345;
    private decimal myDecimal2 = 6.7;

    public void Method()
    {
        System.Console.WriteLine(myDecimal1.ToString(s_DecimalFormat));
        System.Console.WriteLine(myDecimal2.ToString(s_DecimalFormat));
    }
}

回答1:

Theoretically, if you change System.Globalization.CultureInfo.CurrentCulture to something that formats a decimal the way you want, this would work. It will open up a huge can of worms you don't want to touch with a ten-foot pole. Do not do this. Change all your calls. Maybe write a method for it.



回答2:

A extension method might be nice here. Something like:

public static string ToMyString(this decimal value)
{
   return value.ToString("your formatting");
}

I agree with @nvoigt that changing the globalization settings is a bad idea



回答3:

You could write your own extension method. As an example:

public class Test
{

    private void DoStuff()
    {

        Decimal d = new Decimal();
        d = 0.5M;

        Console.WriteLine("{0}", d);
        Console.WriteLine("{0}", d.ToCustomString());

    }

}

public static class Extensions
{
    public static string ToCustomString(this Decimal number)
    {
        return string.Format("Blah {0}", number.ToString());
    }
}

Output:

0.5
Blah 0.5

When using Decimal.ToCustomString instead of ToString, at least in this case, the decimals are prefaced with "Blah "

You can write the extension method in the format that you would like to return, granted you would need to use the extension method rather than .ToString()