精选圈子榜单优站
编程综合
编程综合
技术
20关注
编程技术记录、分享 ,记录你的编程生活点点滴滴!

数字转汉字工具类




/**
* 数字转汉字工具类
*
* @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));
}
}

  • 若文章侵犯了您的权益,请联系我们进行处理。

  • 2017-09-12
  • 2086阅读
评论