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:
- (12345.00).ToString(…) should display as 12345
- (12345.10).ToString(…) should display as 12345.10
- (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.)
Something along these lines?
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.