Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Format an integer to use a thousands separator without decimal places or leading 0 for small integers

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?

like image 273
Justin Avatar asked Nov 03 '09 09:11

Justin


People also ask

How do you format a string to show two decimal places?

String strDouble = String. format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you make a separator in numbers?

Place the cursor at the location you want to insert the 1000 separator, click Insert > Symbol > More Symbols. 2. In the Symbol dialog, under Symbols tab select Verdana from Font drop-down list, then select Basic Latin from Subset drop-down list, now select the 1000 separator from the list, click Insert to insert it.


4 Answers

This worked for me.

String.Format("{0:#,0} {1:#,0}", 5, 5000); // 5 5,000 
like image 189
Richard Friend Avatar answered Sep 22 '22 13:09

Richard Friend


Try this:-

String.Format("{0:n0}",5000) // 5,000 String.Format("{0:n0}",5) // 5 String.Format("{0:n0}",0) // 0 
like image 34
ZafarYousafi Avatar answered Sep 25 '22 13:09

ZafarYousafi


String.Format("{0:#,0} {1:#,0}", 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.]. EDIT: You'll definitely want one as the last digit in the pattern, or a zero value will be rendered as an empty String
  • # means don't put anything into the output unless there's a significant digit here.

EDIT (thanks @eulerfx):

  • the last portion needs to be a 0 rather than a # (as I initially had it) as a value of zero would otherwise be rendered as a zero-length string.
like image 25
Ruben Bartelink Avatar answered Sep 25 '22 13:09

Ruben Bartelink


Try

String.Format("{0:#,#}", 4000);
like image 39
Anax Avatar answered Sep 26 '22 13:09

Anax