简体   繁体   中英

Override decimal ToString() method

I have a decimal datatype with a precision of (18, 8) in my database and even if its value is simply 14.765 it will still get displayed as 14.76500000 when I use Response.Write to return its value into a webpage.

Is it possible to override its default ToString method to return the number in the format #,###,##0.######## so that it only displays relevant decimal places?

UPDATE

I'm assuming that when one outputs number on a page like <%= item.price %> (where item.price is a number) that the number's ToString method is being called?

I'm trying to avoid having to change every instance where the value is displayed by defaulting the ToString() format somehow.

您不想重写ToString() ,您想调用ToString()并指定IFormatProvider格式化String

You can't override ToString for decimal type since it's a struct .

But you can use extension methods to do so:

public static class DecimalExtensions
{
      public static string ToString(this decimal some, bool compactFormat)
      {
            if(compactFormat) 
            {
                return some.ToString("#,###,##0.########");
            }
            else
            {
                return some.ToString();
            }
      }
}

So now you can do this:

string compactedDecimalText = 16.38393m.ToString(true);

I ran into the same problem as you. People wanted decimals to be formatted in crazy custom ways throughout the application.

My first idea was to create a wrapper around Decimal and override the ToString() method.

Although you cannot inherit from Decimal, you can create a type that implicitly casts to and from a Decimal.

This creates a facade in front of Decimal, and gives you a place to write custom formatting logic.

Below is my possible solution, let me know if this works or if this is a horrible idea.

public struct Recimal
{

    private decimal _val;
    public Recimal(decimal d) { _val = d; }

    public static implicit operator Recimal(decimal d)
    {
        return new Recimal(d);
    }

    public static implicit operator Decimal(Recimal d)
    {
        return d._val;
    }

    public override string ToString()
    {
        //if negative, show the minus sign to the right of the number
        if (_val < 0)
            return String.Format("{0:0.00;0.00-;}", _val);

        return _val.ToString();
    }

}

It works just like a Decimal:

        Decimal d = 5;
        Recimal r = -10M;
        Recimal result = r + d;

        //result: 5.00-
        textBox1.Text = result.ToString();

Why not use string.Format() directly on double ?

Here are some references for the formatting options:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM