0

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.

2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by jasscat
0

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 by Reverend Jim: Fixed formatting

0

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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.