Android 数字转中文

前两天公司同事在群里扔了一个小case让大家换换脑子,把数字转换为会计上使用的大写汉字,想想也挺有意思的,就写了给小Demo。具体的不多说了,直接看代码吧,一个挺实用的简单例子

 


    public static String[] chineseCode = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    private static String unit[][] = { { "", "万", "亿"}, { "", "拾", "佰", "仟"}};
    private static String[] elseUnit = {"分", "角"};

    private static double[] doubles = {0, 100, 123.45, 2010.23, 29234.04, 303000, 400060, 500089, 7896543, 987654321.5, 2018, 2005};

    public static void main(String[] args) {
        for (int i = 0; i < doubles.length; i++) {
            System.out.println(doubles[i]);
            System.out.println(isDouble(doubles[i]));
        }
    }

 

  /**
     * 判断是否为整数
     *
     * @param num
     * @return
     */
    private static String isDouble(double num) {
        String s = "";
        String numString = String.format("%.2f", num);
        String[] strings = numString.split("\\.");
        if (num == 0) {
            s = "零圆整";
        } else {
            s += getString(false, strings[0]) + getString(true, strings[1]);
        }
        return s;
    }
/**
     * 最后返回结果
     *
     * @return
     */
    private static String getString(boolean isPoint, String snum) {
        String result = "";
        String[] numArray = snum.split("");
        //判断是整数部分还是小数部分
        if (isPoint) {
            //小数部分
            //判断是否是00
            if (snum.equals("00")) {
                // 00加圆整
                result += "圆整";
            } else {
                result+="圆";
                //非00需要加角分单位
                for (int i = 0; i < numArray.length; i++) {
                    int value = Integer.valueOf(numArray[i]) % 10;
                    result += (chineseCode[value] + elseUnit[numArray.length - 1 - i]);
                }
            }
        } else {
            //整数部分
            int integerPart = (int) Math.floor(Double.valueOf(snum));
            for (int i = 0; i < unit[0].length && integerPart > 0; i++) {
                String p = "";
                for (int j = 0; j < unit[1].length; j++) {
                    //每次除以10确定当前大写汉字是什么
                    p = chineseCode[integerPart % 10] + unit[1][j] + p;
                    integerPart = integerPart / 10;
                }
                //使用正则去判断0
                result = p.replaceAll("(零.)*零$", "")+ unit[0][i]+result;
            }
        }
        //把多余的零替换掉
        result=result.replaceAll("(零.)+", "零");
        if (result.substring(0,1).equals("零")){
            result=result.substring(1,result.length());
        }
        return result;
    }

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值