public Double CNYtoN(String amount) { double result = 0; double temp = -1;//存放一個單位的數字如:十萬 int count = 0;//判斷是否有chArr Map<Character, Double> map = new HashMap<Character, Double>(); //存放數字map map.put('壹', 1.0); map.put('貳', 2.0); map.put('叄', 3.0); map.put('肆', 4.0); map.put('伍', 5.0); map.put('陸', 6.0); map.put('柒', 7.0); map.put('捌', 8.0); map.put('玖', 9.0); Map<Character, Double> map1 = new HashMap<Character, Double>(); //存放單位map map1.put('拾', 10.0); map1.put('佰', 100.0); map1.put('仟', 1000.0); map1.put('萬', 10000.0); map1.put('億', 100000000.0); map1.put('角', 0.1); map1.put('分', 0.01); map1.put('厘', 0.001); for (int i = 0; i < amount.length(); i++) { //遍歷屬組 char c = amount.charAt(i); for (Map.Entry<Character, Double> entry : map.entrySet()) { //遍歷數字map boolean flag = false; if (c == entry.getKey()) { if (temp != -1) { result += temp; temp = -1; } temp = entry.getValue(); break; } else { if (temp == -1) { continue; } for (Map.Entry<Character, Double> entry1 : map1.entrySet()) {//遍歷單位map if (c == entry1.getKey()) { temp *= entry1.getValue(); flag = true; break; } } } if (flag) { break; } } if (i == amount.length() - 1) { result += temp; } } return result; }
測試Demo
public static void main(String[] args) { CNYtoNum c = new CNYtoNum(); System.out.println(c.chineseNumber2Int("壹萬伍仟肆佰壹拾元貳角捌分肆厘")); }
原創。性能待優化
優化版本如下:
public Double CNYtoN(String amount) { double result = 0; double temp = -1;//存放一個單位的數字如:十萬 int count = 0;//判斷是否有chArr Map<Character, Double> map = new HashMap<Character, Double>(); //存放數字map map.put('壹', 1.0); map.put('貳', 2.0); map.put('叄', 3.0); map.put('肆', 4.0); map.put('伍', 5.0); map.put('陸', 6.0); map.put('柒', 7.0); map.put('捌', 8.0); map.put('玖', 9.0); Map<Character, Double> map1 = new HashMap<Character, Double>(); //存放單位map map1.put('拾', 10.0); map1.put('佰', 100.0); map1.put('仟', 1000.0); map1.put('萬', 10000.0); map1.put('億', 100000000.0); map1.put('角', 0.1); map1.put('分', 0.01); map1.put('厘', 0.001); for (int i = 0; i < amount.length(); i++) { //遍歷屬組 char c = amount.charAt(i); if (map.containsKey(c)) { if (temp != -1) { result += temp; temp = -1; } temp = map.get(c); } else { if (temp == -1) { continue; } if (map1.containsKey(c)) { temp *= map1.get(c); } } if (i == amount.length() - 1) { result += temp; } } return result; }
減少遍歷嵌套。提升性能。
