C# Number Format

Format a number with commas:

int i = 10000000;
string s = i.ToString("N"); //10,000,000.00
string s2 = i.ToString("00,000,000"); //10,000,000
string s3 = i.ToString("#,0"); //10,000,000

Format a decimal number with commas:
double i = 10000000.3469;
string s = i.ToString("#,0.000"); //10,000,000.347
string s2 = i.ToString("#,0.00"); //10,000,000.35

Format a number with leading zeros:
int i = 42;
string s = i.ToString("D4"); //0042
string s2 = i.ToString("D5"); //00042
string s3 = i.ToString().PadLeft(5,'0'); //00042
string s4 = i.ToString().PadLeft(5,'%'); //%%%42

Format a decimal to specified decimal places:
double i = 10000000.3469;
string s = i.ToString("0.000"); //10000000.347
string s2 = i.ToString("#,0.000"); //10,000,000.347



endmemo.com © 2017  Terms of Use | Home