日期:2014-05-20 浏览次数:20792 次
public static void formatMoney(String money) { if (!money.matches("(?!(\\.|[0]{2,}))[\\d\\.]*(?<!\\.)")){ System.out.println("Invalid Number"); return; } int integralNumber = money.indexOf('.'); int newCharLength = (integralNumber - 1) / 3 + money.length(); char[] c = new char[newCharLength]; for (int i = integralNumber % 3; i < integralNumber; i += 3) { if (i != 0) { c[i++] = ','; } } int count = 0; for (int i = 0; i < newCharLength; i++) { if (c[i] != ',') { c[i] = money.charAt(count++); } } System.out.println("The answer is: "); System.out.println(c); }
------解决方案--------------------
public class Test { public static void main(String[] args) { String str = "1234567"; System.out.println(formatMoney(str)); str = "1234567.10"; System.out.println(formatMoney(str)); } public static String formatMoney(String money) { if(!money.matches("\\d+(\\.\\d{1,2})?")) { throw new IllegalArgumentException("money format error!"); } int pointIndex = money.indexOf("."); if(pointIndex < 0) { money = money + ".00"; } if(pointIndex == money.length() - 2) { money = money + "0"; } money = money.replaceAll("(?<=\\d)(?=(?:\\d\\d\\d)+\\.)", ","); return money; } }
------解决方案--------------------
使用DecimalFormat或者,你有时间,也可以试试NumberFormat
同意2楼的做法。
------解决方案--------------------
money = money.replaceAll("(?<=\\d)(?=(?:\\d\\d\\d)+\\.)", ",");