package com.diagbot.util; import java.math.BigDecimal; /** * @description: 年龄工具类 * @author: zhoutg * @time: 2020/7/30 15:18 */ public class AgeUtil { /** * 年龄字符串转换成double类型 * * @param ageStr * @return */ public static Double convertAge(String ageStr) { try { // 防止程序出错 if (StringUtil.isEmpty(ageStr)) { return 20.0; } // 数值,当成年龄处理 if (isNumbers(ageStr)) { return Double.parseDouble(ageStr); } // 20日 | 20天 if (ageStr.endsWith("日") || ageStr.endsWith("天")) { return getHalfUp((Double.parseDouble(ageStr.substring(0, ageStr.length() - 1))) / 365); } // 3岁 if (ageStr.endsWith("岁")) { return Double.parseDouble(ageStr.substring(0, ageStr.length() - 1)); } // 3岁7个月 | 3岁7月 if (ageSuiYue(ageStr)) { String[] ageArr = new String[2]; int indexSui = ageStr.indexOf("岁"); ageArr[0] = ageStr.substring(0, indexSui); if (ageStr.indexOf("个月") > -1) { // 3岁7个月 ageArr[1] = ageStr.substring(indexSui + 1, ageStr.indexOf("个月")); } else { // 3岁7月 ageArr[1] = ageStr.substring(indexSui + 1, ageStr.indexOf("月")); } return Double.parseDouble(ageArr[0]) + getHalfUp(Double.parseDouble(ageArr[1]) / 12); } // 1.08月 | .11月 | 3月 if (ageYue(ageStr)) { String noUnit = ageStr.substring(0, ageStr.length() - 1); return getHalfUp(Double.parseDouble(noUnit) / 12); } } catch (Exception e) { e.printStackTrace(); return 20.0; } return 20.0; } /** * 判断字符串是否 仅 包含数字 * * @param str * @return */ public static boolean numbersOnly(String str) { String regex = "^[0-9]+$"; return str.matches(regex); } /** * 判断字符串是否数值(正) * * @param str * @return */ public static boolean isNumbers(String str) { String regex = "[0-9]+|([0-9]+\\.)+[0-9]*|[0-9]*(\\.[0-9]+)+"; return str.matches(regex); } /** * 判断年龄字符串:xx月 * * @param str * @return */ 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}个{0,1}月$"; 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(); } }