From 9de5aef0e121d9a6e4e970278b998e7aa279b040 Mon Sep 17 00:00:00 2001
From: JTongChen <819250131@qq.com>
Date: Thu, 18 Apr 2024 21:10:54 +0800
Subject: [PATCH] =?UTF-8?q?feat:=20NumberChineseFormatter=E6=8F=90?=
=?UTF-8?q?=E4=BE=9B=E9=98=BF=E6=8B=89=E4=BC=AF=E8=BD=AC=E4=B8=AD=E6=96=87?=
=?UTF-8?q?=E6=94=AF=E6=8C=81=E5=A4=9A=E4=BD=8D=E5=B0=8F=E6=95=B0=E7=9A=84?=
=?UTF-8?q?=E6=96=B9=E6=B3=95?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../core/convert/NumberChineseFormatter.java | 49 +++++++++++++++++++
1 file changed, 49 insertions(+)
diff --git a/hutool-core/src/main/java/cn/hutool/core/convert/NumberChineseFormatter.java b/hutool-core/src/main/java/cn/hutool/core/convert/NumberChineseFormatter.java
index 71fd6fa1d..c9a45d90c 100644
--- a/hutool-core/src/main/java/cn/hutool/core/convert/NumberChineseFormatter.java
+++ b/hutool-core/src/main/java/cn/hutool/core/convert/NumberChineseFormatter.java
@@ -2,11 +2,15 @@ package cn.hutool.core.convert;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
+import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import java.math.BigDecimal;
import java.math.RoundingMode;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
/**
* 数字转中文类
@@ -43,6 +47,18 @@ public class NumberChineseFormatter {
new ChineseUnit('亿', 1_0000_0000, true),
};
+ /**
+ * 口语化映射
+ */
+ private static final Map COLLOQUIAL_WORDS = new HashMap() {
+ {
+ put("一十", "十");
+ put("一拾", "拾");
+ put("负一十", "负十");
+ put("负一拾", "负拾");
+ }
+ };
+
/**
* 阿拉伯数字转换成中文,小数点后四舍五入保留两位. 使用于整数、小数的转换.
*
@@ -220,6 +236,39 @@ public class NumberChineseFormatter {
return chinese;
}
+ /**
+ * 阿拉伯数字转换成中文. 使用于整数、小数的转换.
+ * 支持多位小数
+ *
+ * @param amount 数字
+ * @param isUseTraditional 是否使用繁体
+ * @param isUseColloquial 是否使用口语化(e.g. 一十 -> 十)
+ * @return 中文
+ */
+ public static String format(BigDecimal amount, boolean isUseTraditional, boolean isUseColloquial) {
+ String formatAmount;
+ if (amount.scale() <= 0) {
+ formatAmount = NumberChineseFormatter.format(amount.longValue(), isUseTraditional);
+ } else {
+ List numberList = StrUtil.split(amount.toPlainString(), CharUtil.DOT);
+ // 小数部分逐个数字转换为汉字
+ StringBuilder decimalPartStr = new StringBuilder();
+ for (char decimalChar : numberList.get(1).toCharArray()) {
+ decimalPartStr.append(NumberChineseFormatter.numberCharToChinese(decimalChar, isUseTraditional));
+ }
+ formatAmount = NumberChineseFormatter.format(amount.longValue(), isUseTraditional) + "点" + decimalPartStr;
+ }
+ if (isUseColloquial) {
+ for (Map.Entry colloquialWord : COLLOQUIAL_WORDS.entrySet()) {
+ if (formatAmount.startsWith(colloquialWord.getKey())) {
+ formatAmount = formatAmount.replaceFirst(colloquialWord.getKey(), colloquialWord.getValue());
+ break;
+ }
+ }
+ }
+ return formatAmount;
+ }
+
/**
* 数字字符转中文,非数字字符原样返回
*