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.
You don't want to override ToString()
, you want to call ToString()
and specify an IFormatProvider
or a formatting 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With