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:
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With