Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying trailing zeros except when a whole number

Tags:

c#

.net

Is there a way (in .NET) of removing trailing zeros from a number when using .ToString("..."), but to display to 2 decimal places if the number is not a whole number:

  1. (12345.00).ToString(...) should display as 12345
  2. (12345.10).ToString(...) should display as 12345.10
  3. (12345.12).ToString(...) should display as 12345.12

Is there 1 number format string that will work in all these scenarios?

.ToString("#.##") nearly works but doesn't show the trailing 0 for scenario 2...

Also, other cultures aren't an issue, i just want a decimal point (not a comma etc.)

like image 202
David_001 Avatar asked Feb 01 '10 13:02

David_001


1 Answers

Something along these lines?

            if (number % 1 == 0)
                Console.WriteLine(string.Format("{0:0}", number));
            else
                Console.WriteLine(string.Format("{0:0.00}", number));

EDIT

There is a little bug in this code though:) 1.001 will be printed as "1.00"... this may not be what you want, if you need to print 1.001 as "1" you'll need to change the if(...) test to check for a finite tolerance. As this question is more about the formatting I will leave the answer unchanged but in production code you might want to consider this kind of issue.

like image 157
Steve Avatar answered Oct 05 '22 22:10

Steve