Custom Number Format Strings: Dynamic Decimal Point

I am trying to format a double in C # so that it uses the thousands separator and adds digits up to 4 decimal places.

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

I currently have:

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

      

thank

+2


source to share


2 answers


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



MSDN lists standard numeric string strings and custom numeric format strings so you can see for yourself that none of them suit your needs.

+6


source


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

If you have "#, ###. 00" you get trailing zeros.

test code:

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

      



Gives output "45". Setting d to 45.45 results in "45.45", which sounds like you after.

So you had an answer in the end!;)

By the way, there is a handy cheat sheet for formatted strings (among other handy cheat sheets) at http://john-sheehan.com/blog/net-cheat-sheets/

+7


source







All Articles