java将金额数字转换成对应的汉字

####记得这是一道面试题,今天中午花时间写了下,贴代码:

import java.util.Scanner;  

public class NumberToWord {  
  
   private static String input;

        private static Scanner sc;

        private static String[] num = {"零","一","二","三","四","五","六","七","八","九","十"};

        private static String[] unit = {"","十","百","千","万","十","百","千","亿"};

        private static String[] result;

        private static void input() {
            System.out.println("请输入一串数字最多9位");
            sc = new Scanner(System.in);
            input = sc.nextLine();
        }

        public static String transfer(String input) {
            String out = "";
            result = new String[input.length()];
            int length = result.length;
            for(int i = 0; i< length; i++) {
                result[i] = String.valueOf(input.charAt(i));
            }
            for(int i = 0; i< length; i++) {
                int back;
                if(!result[i].equals("0")) {
                    back = length - i - 1;
                    out += num[Integer.parseInt(result[i])];
                    out += unit[back];
                } else {
                    //最后一位不考虑
                    if(i == (length - 1)) {
                        if(length > 4 && result[length - 1].equals("0") && result[length - 2].equals("0") && result[length - 3].equals("0") && result[length - 4].equals("0")){
                            out += unit[4];
                        }
                    } else {
                        //九位数,千万,百万,十万,万位都为0,则不加“万”
                        if(length == 9 && result[1].equals("0") && result[2].equals("0") && result[3].equals("0") && result[4].equals("0")) {

                        } else {
                            //大于万位,连着的两个数不为0,万位等于0则加上“万”
                            if(length > 4 && !result[i+1].equals("0") && result[length -5].equals("0")){
                                out += unit[4];
                            }
                        }
                        //万位之后的零显示
                        if(i == length -4 && !result[i+1].equals("0")) {
                            out += num[0];
                        }
                    }
                }
            }
            return out;
        }
        public static void main(String[] args) {
            input();
            System.out.println(transfer(input));
        }
  
}

运行结果:

请输入一串数字最多9位
10002345
一千万二千三百四十五
请输入一串数字最多9位
972364521
九亿七千二百三十六万四千五百二十一
请输入一串数字最多9位
300000
三十万
    原文作者:-夏夜凉月-
    原文地址: https://blog.csdn.net/cool_summer_moon/article/details/56680073
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞