custom number formatting in C#

One of the painful things about good old ASP was string formatting; VBScript simply didn't have anything useful. C# do, but MSDN doesn't provide a quick reference to the formatting options. So here's a quick reference. The C# equivalent for sprintf is String.Format, which takes a format string and the arguments. It returns a string, and because you're not passing in a buffer there's no chance of a buffer overflow.

string outputString = String.Format("At loop position {0}.\n", i);

The ToString method can accept a string parameter which tells the object how to format itself. In the call to String.Format , the formatting string is passed after the position, for example, "{0:##}". The text inside the curly braces is {argumentIndex[,alignment][:formatString]}. If alignment is positive, the text is right-padding to fill the specified field length, if it's negative, it's left-padded.custom number formatting

specifier type format output
(double 1234.56)
0 zero placeholder {0:00.000} 1234.560
# digit placeholder {0:#.##} 1234.56
. decimal point placeholder {0:0.0} 1234.6
, thousand separator {0:0,0} 1,235
% percentage {0:0%} 123456%


Some of the code i tried...

//decimal stingDate = Convert.ToDecimal( "79798797987.96999797696");
//string stgDate = String.Format("{0:$#,##0.00;($#,##0.00);Nothing}", stingDate);
//string stingDate = String.Format("{0:$#,##0.00;($#,##0.00);Nothing}", str);
//MessageBox.Show(stgDate);

string stingDat = System.DateTime.Today.Date.ToShortDateString();
int day = DateTime.Parse(stingDat.ToString()).Day;
MessageBox.Show(day.ToString());
int month = DateTime.Parse(stingDat.ToString()).Month;
MessageBox.Show(month.ToString());
int year = DateTime.Parse(stingDat.ToString()).Year;
MessageBox.Show(year.ToString());
DateTime curSysDate = new DateTime(year, month, day);
MessageBox.Show(curSysDate.ToShortDateString().ToString());

Comments

prathap kumar said…
There is another meaning for comma placeholder character. When the comma character occur on the immediate left of the decimal
point, they act as a scaling factor. Each comma causes the value to be divided by 1,000. for instance

123456789

#,###,.# format specifier returns 123456.8

Prathap Kumar
.Net Training

Popular posts from this blog

ASP.NET website "Cannot read configuration file due to insufficient permissions" in IIS 7 and Windows Server 2008

Error occurred in deployment step 'Install app for SharePoint': The System Account cannot perform this action.

None of the selected features can be installed or upgraded. Setup cannot proceed since no