tags:

views:

122

answers:

4

I am trying to format a decimal so that it will get displayed as so:

14.5 should get displayed as "14.50" 14.50 should get displayed as "14.50" 14.05 should get displayed as "14.05" 14.00 should get displayed as "14"

Is the possible with a single String Format, i.e. not using conditional formatting?

I've tried "0.##" (doesn't satisfy the first example) and "0.00" (doesn't satisfy the last example).

Thanks.

+4  A: 

Yes. You can use the "G" format specifier. For samples, see String.Format's documentation.

For example:

decimal value = 14.05m;
string result = String.Format("{0:G}", value); // "14.05"

value = 14m;
result = String.Format("{0:G}", value); // "14"
Reed Copsey
yes, but 14.5 would still show up as 14.5
Stan R.
Nice, learn something new all the time.
GrayWizardx
mmm - yeah, true. Not sure why 14.5 shouldn't be 14.5, if 14.00 is 14.... That one could get nasty to handle without some extra logic.
Reed Copsey
Just tested, and 14.50 shows up as "14.50" with this method.
jball
Here's the code: decimal value = 14.50m; string result = String.Format("{0:G}", value); // "14.50" And yes, 14.5m shows up as "14.5".
jball
G will use the number of significant digits to determine output. `14.00m` will display "14.00", and `14m` will display "14".
Jeremy Seghi
I'm using this to display money values. So if there is no cents on the amount, then I simply want to display the dollars. If there are cents in the amount then it should be displayed.At present, I always displaying the cents (".00"), even if there are no cents. I just think it would be neater to not display the cents if there aren't away.It's only a minor thing, so if it can't be done with a single String Format, then I'll just leave as is.
Rezler
A: 

I don't think you'll be able to do that without some sort of conditional formatting, because you want the formatting to do different things in different cases.

If you'd settle for 14.5 instead of 14.50, then you'd be OK with the 0.## syntax, but I can't think of a way to do it.

chris
A: 

Follow Reed's answer and add a check after that:

resultArray = result.Split('.');

if (resultArray.Length > 1 && resultArray[1].Length != 2)
    result = String.Format("{0.00}", value);

Not exactly elegant, but will get you the result you desire.

This is assuming the person saying it doesn't apply to 14.5 is correct in the comments.

Aequitarum Custos
+1  A: 

You could use something like: FormatNumber(VariableToBeFormatted, 2).Replace(".00", String.Empty)

Orry