Menu ▼



Posted By :
avatarmrkraju
Total Views : 503

Format Numbers using String.Format in C#

We can format numbers using String.Format method in c#, it will returns a formatted result string.

Example Add leading zeros to number(Fixed length)
You can specify the minimum length of the digits for the input number along with the standard format string "D" it will add the leading zeros for the remaining digits.

In the below example we have mentioned D10 and input value we have given as 7658 so the String.Format will add 6 leading zeros to the input value.

Or you can specify the string format as 10 zeros {0:0000000000} will give you the same output.

int intVal = 7658;
string strMessage = string.Format(String.Format("{0:D10}", intVal));
spnMessage.InnerText = strMessage;

    OR
    
int intVal = 7658;
string strMessage = string.Format(String.Format("{0:0000000000}", intVal));
spnMessage.InnerText = strMessage;

Output
0000007658


More examples

{0,10:000000}
It will add the leading zeros up to 6 digits and adds 4 spaces.

int intVal = 7658;
string strMessage = string.Format(String.Format("{0,10:000000}", intVal));
spnMessage.InnerText = strMessage;
Output
007658


{0,0000000000.0000}
It will add the leading zeros up to 10 digits and adds 4 decimal digits.
int intVal = 7658;
string strMessage = string.Format(String.Format("{0:0000000000.0000}", intVal));
spnMessage.InnerText = strMessage;
Output
0000007658.0000


{0:N2}
It will format number with thousand separator along with 2 decimal digits.
int intVal = 7658;
string strMessage = string.Format(String.Format("{0:N2}", intVal));
spnMessage.InnerText = strMessage;
Output
7,658.00


{0:C}
It will format number with currency along with 2 decimal digits.
int intVal = 7658;
string strMessage = string.Format(String.Format("{0:C}", intVal));
spnMessage.InnerText = strMessage;
Output
$7,658.00






comments powered by Disqus


Search dotnetlearners.com