tags:

views:

417

answers:

6

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.)

+7  A: 

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.

Steve Haigh
For slightly more readable code, I would prefer `String format = (number % 1) == 0 ? "{0:0}" : "{0:0.00}";`
NickLarsen
Yes, I did go with that initialy but I thought the "long way" was clearer in the context of answering the question. I would probably use your style in real code.
Steve Haigh
It's not quite what I was looking for, as I wanted to bind directly to the number on an asp.net page, and use the format string to determine how it is displayed. I have, however, used this approach to add another variable to my bindings, and bind to that (as a string) instead.
David_001
A: 

I can't say I've come across a single mask that will do that. I would use

string output = (value % 1 > 0) ? String.Format("{0:0.00}", value) : String.Format("{0:0.##}", value);
Kamal
+1  A: 

Not in one format but it fits in one line:

double a = 1.0;
string format = string.Format((a == (int)a) ? "{0:0}" : "{0:0.00}", a);
Carra
A: 

I guess you could do your very own method to produce that display, since it's conditional to whether or not it is an integer.

public static class Extensions
{
    public static string ToCustomString(this decimal d)
    {
        int i = (int)d;
        if (i == d)
            return i.ToString();

        return d.ToString("#.00");
    }
}
Dynami Le Savard
+1  A: 

If you want to use it to display currency, you can use following

float fVal = 1234.20f;
String strVal = fVal.Tostring("c");
Mahin
A: 

You could write an extension method like this to do the formatting for you:

public static string FormatNumberString(this double input)
    {
        int temp;
        string inputString = input.ToString();
        return Int32.TryParse(inputString, out temp) ? inputString : input.ToString("0.00");
    }
Keith Rousseau