2

So it is easy enough to optionally format to two decimal places if non-zero i.e:

String.Format("{0:0.##}", 123.451); // 123.45
String.Format("{0:0.##}", 123.4567);

(Taken from https://stackoverflow.com/a/21751068/2482265)

And it's easy enough to format with commas:

String.Format("{0:n}", 1234);

And with commas and no decimals:

String.Format("{0:n0}", 1234);

(Taken from https://stackoverflow.com/a/105793/2482265)

But how about with commas and 2 decimals if decimals are non zero, but otherwise no decimals

So

10000000 -> 10,000,000
10000000.234 -> 10,000,000.23
10000000.05 -> 10,000,000.05

Note that if the solution gives 10000000.1 -> 10,000,000.1

That would be acceptable as although I want 2 decimal places, I am infact not dealing with money, so the 2nd decimal place being zero should mean it is not displayed.

Community
  • 1
  • 1
Adam Knights
  • 2,141
  • 1
  • 25
  • 48

2 Answers2

4

Use the format specifier:

"##,#0.##"

for example

string.Format("{0:##,#0.##}" ,number)

or

number.ToString("##,#0.##");

https://dotnetfiddle.net/yecJnT

BhavO
  • 2,406
  • 1
  • 11
  • 13
  • Check the history. It was downvoted when it was wrong. – sgmoore Jul 29 '15 at 10:50
  • the main concern for @Knightsy was the decimal places, which was addressed first, then i added the group seperator after – BhavO Jul 29 '15 at 10:51
  • This answer will display 0.234 as .23 - if you want to retain the front 0 use sgmoore's answer below or change `#.##` to `0.##`. This is the most complete answer with example so accepting. – Adam Knights Jul 29 '15 at 10:57
1

Try a format specifier of

"#,##0.##"
sgmoore
  • 15,694
  • 5
  • 43
  • 67
  • This also works on first glance, this answer displays 0.234 as 0.23 whereas @BhavO's answer displays .23 - My question was ambiguous for this scenario so this is a good answer as well as far as I can see – Adam Knights Jul 29 '15 at 10:56