Reputation: 20132
How can I insert to a string comma (,) after every 3 position starting from last?
input desired output
9876567846678 9,876,567,846,678
567 567
1234 1,234
I used one method like first divide the whole string by three position and then while merging appending coma by three three position.
Is there any better solution? Is there function available to do this trick in java?
Edit :
LAS_VEGAS answer will format the number based on the locale. But i want to format it to a fixed locale ...
how can i do tht?
Upvotes: 1
Views: 429
Reputation: 59198
Yes, there is a "trick" in Java:
public static String addCommas(int num) {
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setGroupingSeparator(',');
df.setDecimalFormatSymbols(dfs);
return df.format(num);
}
System.out.println(addCommas(123456789));
EDIT: In case you want your output to be independent from locale you can use the method below. It starts from the end so there is no need to reverse the string and should be quite efficient:
public static String addCommas(int num) {
StringBuilder s = new StringBuilder(Integer.toString(num));
for(int i = s.length() - 3; i > 0; i -= 3) {
s.insert(i, ',');
}
return s.toString();
}
Upvotes: 5
Reputation: 16914
Well, you could also use a StringBuilder to do that. Here's a quickly hacked together solution:
StringBuilder sb = new StringBuilder("123456789");
int initLength = sb.length();
for(int i=1; i<initLength; i++){
if(i % 3 == 0){
sb.insert(initLength-i, ",");
}
}
System.out.println(sb);
Upvotes: -1
Reputation: 103797
Have a look at the NumberFormat class, which is entirely used for formatting numbers as textual output.
In particular, an instance of DecimalFormat
using the ,
symbol for separators is what you're looking for. A format pattern of #,##0
for example should output integers as you desire if you have no other constraints.
Upvotes: 2