package cn.cslg.pas.common.utils; import java.math.BigDecimal; import java.util.List; /** * @Author chenyu * @Date 2023/3/28 */ public class MathUtils { private static final String[] DIGITS = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"}; private static final String[] UNITS = {"", "十", "百", "千"}; public static double saveTwoDecimal(double value) { BigDecimal bd = new BigDecimal(value); value = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); return value; } public static String fun(int n, int num) { // n 表示目标进制, num 要转换的值 String str = ""; int yushu; // 保存余数 int shang = num; // 保存商 while (shang > 0) { yushu = shang % n; shang = shang / n; // 10-15 -> a-f if (yushu > 9) { str = (char) ('a' + (yushu - 10)) + str; } else { str = yushu + str; } } return str; } public static int BinaryToDecimal(int binaryNumber) { int decimal = 0; int p = 0; while (true) { if (binaryNumber == 0) { break; } else { int temp = binaryNumber % 10; decimal += temp * Math.pow(2, p); binaryNumber = binaryNumber / 10; p++; } } return decimal; } public static Integer getNotNullMinNum(List nums) { Integer min = 100000; for (Integer i : nums) { if (i != null) { if (i < min) { min = i; } } } return min; } public static String numberToChinese(int num) { if (num == 0) { return "零"; } StringBuilder result = new StringBuilder(); String numStr = Integer.toString(num); int length = numStr.length(); boolean prevZero = false; // 标记前一个字符是否为零 for (int i = 0; i < length; i++) { int digit = numStr.charAt(i) - '0'; int unitIndex = length - i - 1; // 计算单位位置(从高位开始) if (digit == 0) { prevZero = true; } else { if (prevZero) { result.append(DIGITS[0]); prevZero = false; } result.append(DIGITS[digit]); if (unitIndex > 0) { // 个位不添加单位 result.append(UNITS[unitIndex]); } prevZero = false; } } String str = result.toString(); // 处理十位为1的特殊情况(10-19) if (str.startsWith("一十") && str.length() > 1) { str = str.substring(1); } // 清理多余零 str = str.replaceAll("零+", "零"); if (str.endsWith("零")) { str = str.substring(0, str.length() - 1); } return str; } public static String convertToChinese(int num) { if (num < 0 || num > 100) { return ""; } if (num == 0) { return "零"; } if (num == 100) { return "一百"; } int ten = num / 10; int unit = num % 10; StringBuilder result = new StringBuilder(); // 处理十位 if (ten > 0) { if (ten > 1) { // 十位大于1时需添加数字 result.append(DIGITS[ten]); } result.append("十"); } // 处理个位 if (unit > 0 || ten == 0) { // 个位为0且十位存在时不处理,否则需添加 result.append(DIGITS[unit]); } return result.toString(); } }