java--阿拉伯数字转中文数字
生活随笔
收集整理的這篇文章主要介紹了
java--阿拉伯数字转中文数字
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
寫(xiě)在前面
該方法目前只能處理Integer能夠裝得下的值,已經(jīng)處理了【零...】的情況
有實(shí)現(xiàn)思路,僅供參考,發(fā)現(xiàn)問(wèn)題可調(diào)優(yōu)的地方多謝指正
上菜!!!
package com.xxx.util;import javax.validation.constraints.NotNull; import java.util.regex.Matcher; import java.util.regex.Pattern;public class StringUtil {private static final String[] CHINESE_NUMBER = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};private static final String[] UNIT = {"", "十", "百", "千"};private static final String[] MORE_THAN_TEN_THOUSAND = {"", "萬(wàn)", "億"};private static final Pattern zeroPattern = Pattern.compile("[\u96f6]+");public static String convertArabNumToChineseNum(@NotNull Integer arabNum) {String[] split = arabNum.toString().split("");/*** step 1:第一次處理,只需要將數(shù)字轉(zhuǎn)為漢字即可*/StringBuffer dealNum = new StringBuffer();for (int i = 0; i < split.length; i++) {dealNum.append(CHINESE_NUMBER[Integer.parseInt(split[i])]);}/*** step 2:將第一次處理后的數(shù)字保存下來(lái),并清空stringBuffer以供后面使用,也可以重新聲明一個(gè)*/String firstDealNum = dealNum.toString();dealNum.setLength(0);/*** step 3:將數(shù)字從后往前面取,每四位取一次,然后轉(zhuǎn)換成千百十的數(shù)字,比如1234就轉(zhuǎn)換為一千二百三十四* step 4:將數(shù)字拼接起來(lái),順帶加上萬(wàn)億等單位 count為是否已經(jīng)達(dá)到萬(wàn)或者億的數(shù)量級(jí)*/int count = 0;for (int i = firstDealNum.length(); i > 0; i -= 4) {String substring = firstDealNum.substring(i - 4 < 0 ? 0 : i - 4, i);String[] numbers = substring.split("");StringBuffer sb = new StringBuffer();for (int j = 0; j < numbers.length; j++) {String num = numbers[j];String unit = UNIT[numbers.length - 1 - j];if (CHINESE_NUMBER[0].equals(num)) {sb.append(num);}else{sb.append(num).append(unit);}}dealNum.insert(0, MORE_THAN_TEN_THOUSAND[count]);dealNum.insert(0, sb.toString());count++;}/*** step 5:個(gè)位是零的話給他干掉* step 6:將數(shù)字中的【零】【零...】替換為【零】*/if (dealNum.length() - 1 == dealNum.lastIndexOf("零")) {dealNum.deleteCharAt(dealNum.length() - 1);}Matcher matcher = zeroPattern.matcher(dealNum.toString());return matcher.replaceAll("零");}}?
下面是試驗(yàn)結(jié)果
總結(jié)
以上是生活随笔為你收集整理的java--阿拉伯数字转中文数字的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 玩转git之webhook应用初探
- 下一篇: 整理使用移动光猫拨号