62,614
社区成员
发帖
与我相关
我的任务
分享
String pattern="###,###.###";
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
The pound sign (#) denotes a digit, the comma is a placeholder for the grouping separator, and the period is a placeholder for the decimal separator.public static void main(String[] args) {
BigDecimal aa = new BigDecimal("1234567.12");
System.out.println(String.format("%1$,09.2f", aa));
}
public static void main(String[] args) {
BigDecimal aa = new BigDecimal("1234567.12");
System.out.println(addComma(aa.toString()));
}
/**
* 在数字型字符串千分位加逗号
* @param str
* @return
*/
public static String addComma(String str){
boolean neg = false;
if (str.startsWith("-")){ //处理负数
str = str.substring(1);
neg = true;
}
String tail = null;
if (str.indexOf('.') != -1){ //处理小数点
tail = str.substring(str.indexOf('.'));
str = str.substring(0, str.indexOf('.'));
}
StringBuilder sb = new StringBuilder(str);
sb.reverse();
for (int i = 3; i < sb.length(); i += 4){
sb.insert(i, ',');
}
sb.reverse();
if (neg){
sb.insert(0, '-');
}
if (tail != null){
sb.append(tail);
}
return sb.toString();
}