Reputation: 5996
I want to format an integer in such a way that if no. of digits are more than 3, a comma should be inserted at 4th location from right and if no. of digits are more than 6, a comma should be inserted at 4th and 7th location from right i.e.
123 should become 123
1234 should become 1,234
12345 should become 12,345
123456 should become 123,456
1234567 should become 1,234,567
I found similar question on SO and on internet but none helped me resolve this problem.
I know this will lead to String.format(format,arguments)
but I'm unable to specify the 1st parameter i.e. format
.
Any help appreciated.
Upvotes: 0
Views: 65
Reputation: 213261
You can use DecimalFormat to format your integer that way: -
int num = 1234567;
NumberFormat formatter = new DecimalFormat("#,###");
System.out.println("The value is: " + formatter.format(num));
OUTPUT: -
The value is: 1,234,567
Upvotes: 2
Reputation: 8101
Use DecimalFormat
to format your input string
DecimalFormat format = new DecimalFormat("#,###");
int d = 1234;
System.out.println(format.format(d));
Upvotes: 1