我有一个bigDecimal的数,比如
BigDecimal aa = new BigDecimal("1234567.12");
现在需要用String format转换成String类型的 1,234,567.12输出
怎么实现?急,在线等
BigDecimal aa = new BigDecimal("1234567.12");
现在需要用String format转换成String类型的 1,234,567.12输出
怎么实现?急,在线等
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();
}
BigDecimal aa = new BigDecimal("1234567.12");
System.out.println(String.format("%1$,09.2f", aa));
}
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.
把二楼的方法改个名字,处理一下BigDecimal的小数点问题不就可以了吗?