3

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

2 Answers 2

8

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! ;)

Sign up to request clarification or add additional context in comments.

Comments

7

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.

7 Comments

No problem. And yeah, if you want to make the method more convenient, I suggest you just wrap it into an extension method.
This is incorrect. The OP's second format string, #,##0.####, does exactly what they require.
@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: 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.
@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).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.