直接撸代码了
package xxxxxxxxxx;
/**
* Created by LiuXiaoDong on 2020-01-10.
* 数字转汉字工具
*/
public class NumberToChineseUtil {
/**
* 任意 数字 转汉字
*
* @param number
* @return
*/
public static String intToChinese(int number) {
StringBuilder sb = new StringBuilder();
String data = String.valueOf(number);
int index = 0;
while (data.length() > 4) {
String valueStr = data.substring(data.length() - 4);
sb.insert(0, intToChineseUnderW(valueStr));
sb.insert(0, getMaxUnitChinese(index));
index++;
data = data.substring(0, data.length() - 4);
}
sb.insert(0, intToChineseUnderW(data));
return sb.toString();
}
/**
* 万以下转化,不到一万用这个效率高一些
*
* @return
*/
public static String intToChineseUnderW(int number) {
String data = String.valueOf(number);
return intToChineseUnderW(data);
}
/**
* 万以下转化,与上面逻辑不一样。这个会存在 0011的情况上面只会是11
*
* @return
*/
public static String intToChineseUnderW(String data) {
int number = Integer.valueOf(data);
if (data.length() > 4) {
//不处理万以上
return "";
}
if (data.length() == 2 && number / 10 == 1) {
if (number % 10 == 0) {
return "十";
}
return "十" + getChinese(number % 10);
}
StringBuilder stringBuilder = new StringBuilder();
for (int i = data.length() - 1; i >= 0; i--) {
int value = Integer.valueOf(data.substring(i, i + 1));
if (value != 0) {
stringBuilder.insert(0, getUnitChinese(data.length() - i));
}
stringBuilder.insert(0, getChinese(value));
}
String result = stringBuilder.toString();
while (result.contains("零零")) {
result = result.replace("零零", "零");
}
//最后一个零抹去,避免 600 == 六百零
if (result.length() > 0 && "零".equals(result.substring(result.length() - 1))) {
result = result.substring(0, result.length() - 1);
}
return result;
}
/**
* 根据不同的情况获取对应的中文
*
* @param num
* @return
*/
public static String getChinese(int num) {
switch (num) {
case 1:
return "一";
case 2:
return "二";
case 3:
return "三";
case 4:
return "四";
case 5:
return "五";
case 6:
return "六";
case 7:
return "七";
case 8:
return "八";
case 9:
return "九";
case 0:
return "零";
}
return "";
}
/**
* 根据数字的位数返回最大位数的单位
*
* @param length
* @return
*/
public static String getUnitChinese(int length) {
switch (length) {
case 2:
return "十";
case 3:
return "百";
case 4:
return "千";
}
return "";
}
/**
* 根据数字的位数返回对应单位
*
* @param index
* @return
*/
public static String getMaxUnitChinese(int index) {
switch (index) {
case 0:
return "万";
case 1:
return "亿";
case 2:
return "万亿";
//后续可以补充,int到不了。得改成long需要自己改
}
return "";
}
public static void main(String[] args) {
System.out.print(intToChinese(1231231242));
}
}
如果不想闲复制麻烦的兄弟,可以直接下载java文件。地址:https://download.csdn.net/download/u011400848/12101103
网友评论