Browse Source

年龄转换

zhoutg 4 years atrás
parent
commit
48afd9fd54
1 changed files with 39 additions and 10 deletions
  1. 39 10
      src/main/java/com/diagbot/util/CoreUtil.java

+ 39 - 10
src/main/java/com/diagbot/util/CoreUtil.java

@@ -35,8 +35,16 @@ public class CoreUtil {
             if (ageStr.endsWith("岁")) {
                 return Double.parseDouble(ageStr.substring(0, ageStr.length() - 1));
             }
+            // 3岁7个月
+            if (ageSuiYue(ageStr)) {
+                String[] ageArr = new String[2];
+                int indexSui = ageStr.indexOf("岁");
+                ageArr[0] = ageStr.substring(0, indexSui);
+                ageArr[1] = ageStr.substring(indexSui + 1,ageStr.indexOf("个月"));
+                return Double.parseDouble(ageArr[0]) + getHalfUp(Double.parseDouble(ageArr[1]) / 12);
+            }
             // 1.08月 | .11月 | 3月
-            if (ageStr.endsWith("月")) {
+            if (ageYue(ageStr)) {
                 String noUnit = ageStr.substring(0, ageStr.length() - 1);
                 String[] ageArr = new String[2];
                 String[] splitArr = noUnit.split("\\.");
@@ -57,31 +65,52 @@ public class CoreUtil {
             }
         } catch (Exception e) {
             e.printStackTrace();
-            log.error("年龄转换异常。" + ageStr);
             return 20.0;
         }
         return 20.0;
     }
 
     /**
-     * 四舍五入保留2位小数
+     * 判断字符串是否 仅 包含数字
      *
-     * @param ageStr
+     * @param str
      * @return
      */
-    public static Double getHalfUp(Double ageStr) {
-        BigDecimal bg = new BigDecimal(String.valueOf(ageStr));
-        return bg.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
+    public static boolean numbersOnly(String str) {
+        String regex = "^[0-9]+$";
+        return str.matches(regex);
     }
 
     /**
-     * 判断字符串是否 仅 包含数字
+     * 判断年龄字符串:xx月
      *
      * @param str
      * @return
      */
-    public static boolean numbersOnly(String str) {
-        String regex = "^[0-9]+$";
+    public static boolean ageYue(String str) {
+        String regex = "^[0-9]*[\\.]*[0-9]{1,2}月$";
+        return str.matches(regex);
+    }
+
+    /**
+     * 判断年龄字符串:3岁7个月
+     *
+     * @param str
+     * @return
+     */
+    public static boolean ageSuiYue(String str) {
+        String regex = "^[0-9]{1,3}岁[0-9]{1,2}个月$";
         return str.matches(regex);
     }
+
+    /**
+     * 四舍五入保留2位小数
+     *
+     * @param ageStr
+     * @return
+     */
+    public static Double getHalfUp(Double ageStr) {
+        BigDecimal bg = new BigDecimal(String.valueOf(ageStr));
+        return bg.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
+    }
 }