本文共 2551 字,大约阅读时间需要 8 分钟。
public class MoneyUtils { private static final String UNIT = "万千佰拾亿千佰拾万千佰拾元角分"; private static final String DIGIT = "零壹贰叁肆伍陆柒捌玖"; private static final double MAX_VALUE = 9999999999999.99D; /** * 将double类型的元转换成中文格式 */ public static String change(double v) { if (v < 0 || v > MAX_VALUE) { return "参数非法!"; } long l = Math.round(v * 100); if (l == 0) { return "零元整"; } String strValue = l + ""; // i用来控制数 int i = 0; // j用来控制单位 int j = UNIT.length() - strValue.length(); String rs = ""; boolean isZero = false; for (; i < strValue.length(); i++, j++) { char ch = strValue.charAt(i); if (ch == '0') { isZero = true; if (UNIT.charAt(j) == '亿' || UNIT.charAt(j) == '万' || UNIT.charAt(j) == '元') { rs = rs + UNIT.charAt(j); isZero = false; } } else { if (isZero) { rs = rs + "零"; isZero = false; } rs = rs + DIGIT.charAt(ch - '0') + UNIT.charAt(j); } } if (!rs.endsWith("分")) { rs = rs + "整"; } rs = rs.replaceAll("亿万", "亿"); return rs; } /** * 将金额分转换成12,131.23格式的元 * 1000131 -> 10,001.31 * 100.31 -> 100.31 * 12 -> 0.12 * 100 -> 1 * 110 -> 1.1 * 10 -> 0.1 * 1 -> 0.01 * 0 -> 0 * @param amountFen 要转换的金额 单位为分 * @param grouping 是否以 10,001.31形式展示,否 则为10001.31 * @param tailTrim 是否去除小数点后的0 * @return String */ public static String fromFenToYuan(Long amountFen,boolean grouping,boolean tailTrim){ String pattern = (amountFen == 0L) ? "0.00" : ",##0.00"; BigDecimal amountYuan = Money.toYuan(amountFen); DecimalFormat decimalFormat = new DecimalFormat(pattern); String formatString = decimalFormat.format(amountYuan); if (!grouping) { formatString = formatString.replaceAll(",",""); } if (!tailTrim) { return formatString; } if (".00".equals(formatString.substring(formatString.length() - 3))) { return formatString.substring(0,formatString.length() - 3); } if ("0".equals(formatString.substring(formatString.length() - 1))) { return formatString.substring(0,formatString.length() - 1); } return formatString; }}
转载地址:http://mbpvn.baihongyu.com/