How do I format a decimal number so that, if there are one or two digits to the right of the decimal point, that shows up (e.g. 123.45) but, if there are digits of zero to the right of the decimal point, the number is formatted as a whole number (e.g. 123.00 shows as 123)?

I know how to specify formatting such that you always show a certain number of decimal places (e.g. ToString("N2") will show 123 as 123.00) but I'm not sure how to show no decimal places if there are zero digits to the right of the decimal point.

This works with me:

        decimal dec = 123.4567M;
        string str = dec.ToString("0.##");
        MessageBox.Show(str);
        MessageBox.Show(String.Format("{0:0.##}", dec));
        dec = 123.0M;
        str = dec.ToString("0.##");
        MessageBox.Show(str);
        MessageBox.Show(String.Format("{0:0.##}", dec));

Edited 3 Years Ago by Reverend Jim: Fixed formatting

That works for me too. I used decimal.ToString("0.##"). I must have misread the documentation. I thought that would always put two decimal places to the right of the decimal point.

Thanks!

This question has already been answered. Start a new discussion instead.