Nemo

Nemo 关注TA

路漫漫其修远兮,吾将上下而求索。

Nemo

Nemo

关注TA

路漫漫其修远兮,吾将上下而求索。

  •  普罗旺斯
  • 负责帅就完事了
  • 写了1,493,291字

该文章投稿至Nemo社区   Java  板块 复制链接


数字转汉字工具类

发布于 2017/09/12 11:12 1,649浏览 0回复 1,809



/**
* 数字转汉字工具类
*
* @author:Nemo 2017714
*/
public class NumberUtils {

private static final String[] UNITS = {"", "", "", "", "", "", "", "", "亿", "", "", "",};

private static final String[] NUMS = {"", "", "", "", "", "", "", "", "", "",};

/**
* 数字转换成中文汉字
*
* @param value 要转换的数字
* @return 返回数字转后的汉字字符串
*/
public static String number2Chinese(int value) {

String result = ""; // 转译结果

for (int i = String.valueOf(value).length() - 1; i >= 0; i--) {// String.valueOf(value)
// 转换成String型得到其长度
// 并排除个位,因为个位不需要单位
int r = (int) (value / Math.pow(10, i));// value / Math.pow(10, i) 截位匹配单位
result += NUMS[r % 10] + UNITS[i];
}

result = result.replaceAll("[, , ]", "");// 匹配字符串中的 "[, , ]" 替换为 ""
result = result.replaceAll("+", "");// 匹配字符串中的1或多个 "" 替换为 ""
result = result.replaceAll("([, 亿])", "$1");
result = result.replaceAll("亿万", "亿"); // 亿万位拼接时发生的特殊情况

if (result.startsWith("一十")) { // 判断是否以 "一十" 开头 如果是截取第一个字符
result = result.substring(1);
}

if (result.endsWith("") && result.length()>1) { // 判断是否以 "" 结尾 如果是截取除 "" 外的字符
result = result.substring(0, result.length() - 1);
}

return result;
}

public static void main(String[] args) {
System.out.println(NumberUtils.number2Chinese(2139567804));
System.out.println(NumberUtils.number2Chinese(2000567004));
System.out.println(NumberUtils.number2Chinese(1));
System.out.println(NumberUtils.number2Chinese(10));
System.out.println(NumberUtils.number2Chinese(101));
}
}
点赞(0)

上一个文章:时间格式化工具类

下一个文章:MAC下重置mysql密码

点了个评