日期:2014-05-20  浏览次数:20802 次

谁能帮个忙,写个小程序,在下新手实在不会写,
用StringBuffer里的insert方法把数组中的数用,分开



String[] price = new String[3];
price[0] = "23445.78";
price[1] = "34323445.78";
price[2] = "234323445.78";
然后用,把小数点前面的数从各位起用,每三位分隔开
比如23445.78分割成23,445.78
或者123456789分割成123,456,789.3532
或者12345分割成12,345;
反正能分割成像平时显示的钱数一样就行三位一个逗号
我觉得这个得从小数点的地方往前添加,而不是从前面往后添加逗号,请各位大神帮忙写写这个小程序
最后请大神把数组中的数输出到控制台哈。。。。

------解决方案--------------------

public static void main(String[] args) {
String num = "-1232354234.1254215325";
System.out.println(convert(num));
}

public static String convert(String num) {
if (num == null 
------解决方案--------------------
 !num.matches("\\-?\\d+\\.?\\d+"))
throw new IllegalArgumentException("number is invalid");

int index = num.indexOf(".");
int end = num.startsWith("-") ? 1 : 0;

StringBuilder temp = new StringBuilder(num);

for (int i = (index == -1 ? temp.length() : index) - 3; i > end; i -= 3) {
temp.insert(i, ',');
}
return temp.toString();
}

------解决方案--------------------

NumberFormat nf = new DecimalFormat("###,###.##");
String[] price = new String[3];
price[0] = "23445.78";
price[1] = "34323445.78";
price[2] = "234323445.78";
for(String str : price){
System.out.println(nf.format(Double.valueOf(str)));;
}

------解决方案--------------------

------解决方案--------------------
引用:

NumberFormat nf = new DecimalFormat("###,###.##");