Override Decimal ToString () Method

I have a decimal data type with an accuracy of (18.8) in my database, and even if its value is 14.765, it will display as 14.76500000 when I use Response.Write to return its value to the web page.

Can I override my default ToString method to return a number in the format #,###,##0.######## to display only the corresponding decimal places?

UPDATE

I assume that when you display a number on a page like <%= item.price %> (where item.price is a number) called by the ToString method?

I am trying to avoid the need to change every instance where the value is displayed, the default format is ToString () in some way.

+4
source share
4 answers

You cannot override ToString for the decimal type, since it is a struct .

But you can use extension methods for this:

 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); 
+3
source

You do not want to override ToString() , you want to call ToString() and specify IFormatProvider or formatting String

+6
source

I encountered the same problem as you. People wanted decimal places to be formatted in crazy user-friendly 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 is implicitly dropped into and out of decimal code.

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 terrible 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 the same as decimal:

  Decimal d = 5; Recimal r = -10M; Recimal result = r + d; //result: 5.00- textBox1.Text = result.ToString(); 
+2
source

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

Here are some links for formatting options:

0
source

All Articles