package com.bdip.common.utils;
/**
* @author gx
* @date 20240327
* 数字工具类
* */
public class NumberUtil {
/**
* 转换阿拉伯数字到中文字符
* @param num
* @return
*/
public static String cnNumConvertor(int num) {
if (num==0) {
return "零";
}
final String illegalPrefix = "一十";
final String[] units = {"", "万", "亿", "兆"};
String prefix = "";
if (num < 0) {
prefix = "负";
num = -num;
}
String numStr = String.valueOf(num);
final int metaLen = 4;
int r = numStr.length() - 1;
int l = Math.max(0, r - metaLen + 1);
int unitIndex = 0;
StringBuilder builder = new StringBuilder();
while (r >= 0 && l >= 0) {
builder.insert(0, cnNumMetaConvertor(numStr.substring(l, r + 1)) + units[unitIndex++]);
r = l - 1;
l = Math.max(0, r - metaLen + 1);
}
String res = builder.toString();
if (res.startsWith(illegalPrefix)) {
res = res.substring(1, res.length());
}
return prefix + res;
}
/**
* 按照中文阅读习惯,处理最高4位的 meta 数字集
*
* @param num
* @return
*/
private static String cnNumMetaConvertor(String num) {
final int metaLen = 4;
final String zeroStr = "0";
final String[] cnNums = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
final String[] units = {"千", "百", "十", ""};
StringBuilder builder = new StringBuilder();
int N = num.length();
boolean canNotJudge = N > metaLen || (N < metaLen && num.startsWith(zeroStr));
if (canNotJudge) {
return "";
}
boolean isPreZero = false;
int unitIndex = metaLen - num.length() - 1;
for (int i = 0; i < N; i++) {
++unitIndex;
final int currNum = num.charAt(i) - '0';
final String currNumCn = cnNums[currNum];
final String currUnit = units[unitIndex];
if (currNum == 0) {
if (isPreZero) {
continue;
}
isPreZero = true;
builder.append(currNumCn);
} else {
isPreZero = false;
builder.append(currNumCn);
builder.append(currUnit);
}
}
String res = builder.toString();
return res.endsWith("零") ? res.substring(0, res.length() - 1) : res;
}
}
标签:中文,数字,int,res,builder,num,final,String
From: https://www.cnblogs.com/cnff/p/18138173