tags:

views:

346

answers:

2

I am trying to format a double in C# such that it uses the thousand separator, and adds digits upto 4 decimal places.

This is straight forward except that I dont want to have the decimal point if it is an integer. Is there a way to do this using the custom numeric format strings rather than an if statement of tenary operator?

Currently I have:

string output = dbl.ToString(dbl == (int)dbl ? "#,##0" : "#,##0.####");

Thanks

+5  A: 

No, there is not any built-in format string for this. Your current solution is the best way to accomplish this.

MSDN lists both the standard numeric format strings and custom numeric format strings, so you should be able to see for yourself that none directly matches your needs.

Noldorin
Frustrating but thanks
JDunkerley
No problem. And yeah, if you want to make the method more convenient, I suggest you just wrap it into an extension method.
Noldorin
This is incorrect. The OP's second format string, `#,##0.####`, does exactly what they require.
LukeH
@Luke: Take a closer look before commenting. That format string will format 2.34 and 2.34 for example, which is not whast the OP wants.
Noldorin
@Noldorin: I'm not sure what you meant in your comment. Can you elaborate? As far as I can tell that format string matches the requirements in the question.
LukeH
@Luke: As I see it, if the number is integral, he wants to display no decimal points, whereas is the number is non-integral, he wants to display exactly 4 decimal points (no more, no less).
Noldorin
@Noldorin: I interpreted the "up to 4 decimal places" to mean 0, 1, 2, 3 or 4 places, but no more. Besides, using that second format string on its own generates *exacty the same output* as using the OP's ternary expression. *If* the ternary expression does produce the correct output, then so will the format string alone, so why not just use that?
LukeH
@Luke: Yeah, you have a point there. I was presuming he actually wanted the second format string to be `#,##0.0000`. We need some clarification here from the OP I think.
Noldorin
+3  A: 

I believe your second format string of "#,##0.##" should be exactly what you want -- the # format character is a placeholder that will NOT display zeros.

If you had "#,###.00" then you would get trailing zeros.

test code:

double d = 45.00;
Console.Writeline(d.ToString("#,##0.##"));

Gives output of "45". Setting d to 45.45 gives output "45.45", which sounds like what you're after.

So you had the answer after all! ;)

Incidentally, there's a handy cheat-sheet for format strings (amongst other handy cheat-sheets) at http://john-sheehan.com/blog/net-cheat-sheets/

Dr Herbie