Reputation: 43
If I have an integer that is 100,000
int integer = 100000;
My question is though, what if i wanted to put a comma after the first three digits so it does not look confusing and looks like 100,000
. Also if the user was to change the integer to a million for example how do i then make the code automatically put a comma after the second pair of the third digits so it looks like this 100,000,000
.
Upvotes: 1
Views: 284
Reputation: 1217
You can use DecimalFormat like this:
DecimalFormat myFormatter = new DecimalFormat("###,###,###");
System.out.print(myFormatter.format(value));
Please reder to this page for more info on formatters http://docs.oracle.com/javase/tutorial/java/data/numberformat.html
Upvotes: 0
Reputation: 660
You can use _
to separate the digits of a number in java 7.
http://docs.oracle.com/javase/7/docs/technotes/guides/language/underscores-literals.html
Upvotes: 1
Reputation: 34618
Java doesn't allow commas, but it allows underscores for the same purpose:
int integer = 100_000;
integer = 100_000_000;
If you want to output it with commas, you have to use number formatting, as explained in other answers.
Upvotes: 4
Reputation: 5087
To display a readable represantation of a number, you can use the following.
System.out.println(NumberFormat.getNumberInstance(Locale.US).format(35634646));
Output: 35,634,646
Upvotes: 4