nyoj-1092-数字分隔(二)
java大法好啊
思路:单独拿出整数部分分隔
1 import java.math.BigDecimal; 2 import java.util.Scanner; 3 4 public class Main{ 5 6 public static void main(String[] args) { 7 Scanner cin = new Scanner(System.in); 8 while (cin.hasNext()) { 9 BigDecimal num = new BigDecimal("0"); 10 num = cin.nextBigDecimal(); 11 12 // 判断负数 13 boolean flag = true; 14 if (num.compareTo(BigDecimal.valueOf(0)) < 0) { 15 flag = false; 16 num = num.abs(); 17 } 18 num = num.setScale(2, BigDecimal.ROUND_HALF_UP); 19 // 保留小数部分 20 String str = num.toString(); 21 String tail = str.substring(str.indexOf("."), str.length()); 22 23 // 保留头部 24 StringBuffer head = new StringBuffer(str.substring(0, str.indexOf("."))); 25 26 int j = 0; 27 for (int i = head.length() - 1; i > 0; i--) { 28 if (head.charAt(i) != ',' && ++j == 3) { 29 head.insert(i, ","); 30 j = 0; 31 } 32 } 33 if (flag == true) { 34 System.out.print(head + tail + "\n"); 35 } else { 36 System.out.print("(" + head + tail + ")" + "\n"); 37 } 38 } 39 40 } 41 42 } 43