I want to format a string as a decimal, but the decimal contains some following zeros after the decimal. How do I format it such that those meaningless 0\'s disappear?
Unlike what everybody suggest to use a G
format specifier I would suggest the following to preserve both thousand separator and decimal point while removing extra trailing zeros:
{0:#,#.##}
The result of this format is much better than G in most cases:
String.Format("{0:#,#.##}",25/2.4);
10.42
String.Format("{0:#,#.##}",1000000);
1,000,000
String.Format("{0:#,#.##}",1000000.3600000);
1,000,000.36
And the G
specifier can't really handle all the possible combinations:
String.Format("{0:G29}",25/2.4);
10.416666666666668
String.Format("{0:G2}",25/2.4);
10
String.Format("{0:G29}",1000000.3600000);
1000000.36
String.Format("{0:G2}",1000000.3600000);
1E+06