Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 456
Jimbo Avatar asked Dec 22 '22 08:12

Jimbo


2 Answers

You don't want to override ToString(), you want to call ToString() and specify an IFormatProvider or a formatting String

like image 113
Stealth Rabbi Avatar answered Dec 24 '22 00:12

Stealth Rabbi


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);
like image 38
Matías Fidemraizer Avatar answered Dec 24 '22 01:12

Matías Fidemraizer