views:

1541

answers:

5

Silly question, I want to format an integer so that it appears with the 1000's separator (,), but also without decimal places and without a leading 0.

My attempts so far have been:

String.Format("{0} {1}", 5, 5000);            // 5 5000
String.Format("{0:n} {1:n}", 5, 5000);        // 5.00 5,000.00
String.Format("{0:0,0} {1:0,0}", 5, 5000);    // 05 5,000

The output I'm after is:

5 5,000

Is there something obvious that I'm missing?

+11  A: 
String.Format("{0:#,#} {1:#,#}", 5, 5000); // "5 5,000"
  • 0 in a format string means put the digit that belongs here, or else a [leading/trailing] zero [to make things align, etc.].
  • # means don't put anything into the output unless there's a significant digit here.
Ruben Bartelink
`#` doesn't really put a space anywhere does it? I thought it just did nothing if there isn't a digit to place there...
Svish
@Svish: Good catch, edited, thanks.
Ruben Bartelink
+8  A: 

THis worked for me.

String.Format("{0:#,0} {1:#,0}", 5, 5000)
Richard Friend
+1  A: 

Try

String.Format("{0:#,#}", 4000);
Anax
A: 

Try This

String.Format("{0:0,0} {1:#,##0}", 5, 5000);

Shadow Max
This looks very similar to Richard Friend's answer that was posted in November. In general, we avoid posting duplicates around here, including deleting our own posts that we posted in good faith without realising that the same answer was already present. My answer is also a duplicate, but has arguably redeeming features 1) not too much later 2) extra detail explaining the solution
Ruben Bartelink
A: 

Try This. This works for me String.Format("{0:n0}",5000) // 5,000 String.Format("{0:n0}",5) // 5

ZafarYousafi