Interview question -- complete the conversion of RMB into capital in JAVA

Correct wording of RMB amount in words:
Integer part: zero, one, two, three, four, five, six, seven, eight, nine
Decimal part: angle, minute and centigrade
Digital part: ten, ten, ten, ten million, hundred million, yuan

be careful:
When there is "0" in the Arabic numerals in figures, the Chinese capital shall be written in accordance with the laws of Chinese language, the composition of figures and the requirements to prevent alteration. Examples are as follows:

1. When there is "0" in the middle of Arabic numerals, the word "zero" shall be written in Chinese capital. For example, ¥ 1409.50 shall be written as RMB fourteen hundred and nine point five.

2. When there are several consecutive "0" in the middle of Arabic numerals, only one "zero" can be written in the middle of Chinese capital amount. For example, ¥ 6007.14 should be written as RMB 6007.14.

3. When the ten thousand and Yuan digits of Arabic numerals are "0", or there are several "0" in the middle of the number, and the ten thousand and Yuan digits are also "0", but the thousand and corner digits are not "0", only one zero or no "zero" can be written in the Chinese capital amount,
If ¥ 1680.32, it shall be written in RMB sixteen hundred and eighty point thirty-two, or in RMB sixteen hundred and eighty point thirty-two. For example, ¥ 107000.53 should be written in RMB one hundred and seven thousand and fifty-three cents, or one hundred and seven thousand and fifty-three cents.

4. When the Arabic numeral digit is "0" but the quantile is not "0", the word "zero" shall be written after the Chinese capital amount "Yuan", for example, ¥ 16409.02 shall be written as sixteen thousand four hundred and nine yuan and two cents, and ¥ 325.04 shall be written as three hundred and twenty-five yuan and four cents.

Train of thought analysis:

  • Initialize the RMB amount in words, and the order of digits is required.
  • Verify the incoming string (non empty, special characters)
  • Judge whether the length of the string exceeds the conversion range
  • Judge whether there is a negative number and replace the negative sign
  • Separating integer and decimal parts
  • Judge whether the integer part has reached 10000

Here we use a StringUtils class and a unit test, junit, which need to import dependencies

 <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

The complete code is as follows:

public class ConvertUpMoney {
    //RMB capitalization of integer part
    private static final String[] NUMBERS = {"Fatal Frame", "one", "two", "three", "four", "five", "land", "seven", "eight", "nine"};
    //Digital part
    private static final String[] IUNIT = {"element", "ten", "Hundred", "Thousand", "ten thousand", "ten", "Hundred", "Thousand", "Hundred million", "ten", "Hundred", "Thousand", "ten thousand", "ten", "Hundred", "Thousand"};
    //RMB capital in decimal part
    private static final String[] DUNIT = {"horn", "branch", "Li"};

    //Amount in words converted to Chinese
    public static String toChinese(String str) {
        //Judge whether the input amount string meets the requirements
        if (StringUtils.isBlank(str) || !str.matches("(-)?[\\d]*(.)?[\\d]*")) {
            System.out.println("Sorry, please enter a number!");
            return str;
        }
        //Judge the input amount string
        if ("0".equals(str) || "0.00".equals(str) || "0.0".equals(str)) {
            return "zero yuan";
        }

        //Determine whether there is a minus sign "-"
        boolean flag = false;
        if (str.startsWith("-")) {
            flag = true;
            str = str.replaceAll("-", "");
        }
        //If the input string contains commas, replace with "." 
        str = str.replaceAll(",", ".");

        String integerStr;//Integer part number
        String decimalStr;//Decimal part number


        //Separating integer and decimal parts
        if (str.indexOf(".") > 0) {//Integer part and decimal part
            integerStr = str.substring(0, str.indexOf("."));
            decimalStr = str.substring(str.indexOf(".") + 1);
        } else if (str.indexOf(".") == 0) {//There are only decimal parts. 34
            integerStr = "";
            decimalStr = str.substring(1);
        } else { //Only integer part 34 exists
            integerStr = str;
            decimalStr = "";
        }

        //The integer part exceeds the computing power and is returned directly
        if (integerStr.length() > IUNIT.length) {
            System.out.println(str + ": Beyond computing power");
            return str;
        }

        //The integer part is stored in the array to dynamically get the corresponding value in the string array
        int[] integers = toIntArray(integerStr);

        //Judge whether there is input 012 in the integer part
        if (integers.length > 1 && integers[0] == 0) {
            System.out.println("Sorry, please enter a number!");
            if (flag) {
                str = "-" + str;
            }
            return str;
        }
        boolean isWan = isWanUnits(integerStr);//Set 10000 units

        //The decimal part is stored in the array
        int[] decimals = toIntArray(decimalStr);

        String result = getChineseInteger(integers, isWan) + getChineseDecimal(decimals);//Returns the final amount in words

        if (flag) {
            return "negative" + result;//If it's negative, add "negative"
        } else {
            return result;
        }
    }

    //Convert string to int
    private static int[] toIntArray(String number) {
        //Initialize one-dimensional array length
        int[] array = new int[number.length()];
        //Loop traversal assignment
        for (int i = 0; i < number.length(); i++) {
            array[i] = Integer.parseInt(number.substring(i, i + 1));
        }
        return array;
    }

    //Convert the integer part to capital
    public static String getChineseInteger(int[] integers, boolean isWan) {
        StringBuffer chineseInteger = new StringBuffer("");
        int length = integers.length;
        // "0. For the input string." 0 after being stored in the array
        if (length == 1 && integers[0] == 0) {
            return "";
        }
        for (int i = 0; i < length; i++) {
            String key = "";//0325464646464
            if (integers[i] == 0) {
                if ((length - i) == 13)//Ten thousand (hundred million)
                    key = IUNIT[4];
                else if ((length - i) == 9) {//Hundred million
                    key = IUNIT[8];
                } else if ((length - i) == 5 && isWan) {//ten thousand
                    key = IUNIT[4];
                } else if ((length - i) == 1) {//element
                    key = IUNIT[0];
                }
                if ((length - i) > 1 && integers[i + 1] != 0) {
                    key += NUMBERS[0];
                }
            }
            chineseInteger.append(integers[i] == 0 ? key : (NUMBERS[integers[i]] + IUNIT[length - i - 1]));
        }
        return chineseInteger.toString();
    }

    //Amount converted from decimal part to capital
    private static String getChineseDecimal(int[] decimals) { //Jiao Fen 038 1 Fen 8 Fen
        StringBuffer chineseDecimal = new StringBuffer("");
        for (int i = 0; i < decimals.length; i++) {
            if (i == 3) {
                break;
            }
            chineseDecimal.append(decimals[i] == 0 ? "" : (NUMBERS[decimals[i]] + DUNIT[i]));
        }
        return chineseDecimal.toString();
    }

    //Judge whether the current integer part has reached [10000]
    private static boolean isWanUnits(String integerStr) {
        int length = integerStr.length();
        if (length > 4) {
            String subInteger = "";
            if (length > 8) {
                subInteger = integerStr.substring(length - 8, length - 4);
            } else {
                subInteger = integerStr.substring(0, length - 4);
            }
            return Integer.parseInt(subInteger) > 0;
        } else {
            return false;
        }
    }

Code test:

  • Test with '0' in Arabic numerals
  • Test under special circumstances (special characters, negative numbers, exceeding the range of RMB values).
 @Test
    public void test() {
        String number = "1409.50";
        String afterStr = ConvertUpMoney.toChinese(number);
        System.out.println(number + ": " + afterStr);//RMB one thousand four hundred and nine point fifty
    }
    @Test
    public void test2() {
        String number = "6007.14";
        String afterStr = ConvertUpMoney.toChinese(number);
        System.out.println(number + ": " + afterStr);//RMB six thousand seven point fourteen
    }
    @Test
    public void test3() {
        String number = "1680.32";
        String afterStr = ConvertUpMoney.toChinese(number);
        System.out.println(number + ": " + afterStr);//RMB one thousand six hundred eighty point thirty-two
    }
    @Test
    public void test4() {
        String number = "107000.53";
        String afterStr = ConvertUpMoney.toChinese(number);
        System.out.println(number + ": " + afterStr);//One hundred and seven thousand yuan and fifty-three cents
    }
    @Test
    public void test5() {
        String number = "16409.02";
        String afterStr = ConvertUpMoney.toChinese(number);
        System.out.println(number + ": " + afterStr);//Sixteen thousand four hundred and nine yuan and two cents
    }
    @Test
    public void test6() {
        String number = "325.04";
        String afterStr = ConvertUpMoney.toChinese(number);
        System.out.println(number + ": " + afterStr);//Three hundred and twenty five yuan and four Fen
    }

    @Test
    public void test7() {
        String number = "-0325.04";
        String afterStr = ConvertUpMoney.toChinese(number);//Sorry, please enter a number!
        System.out.println(number + ": " + afterStr);
    }

    @Test
    public void test8() {
        String number = "325#sdr";
        String afterStr = ConvertUpMoney.toChinese(number);//Sorry, please enter a number!
        System.out.println(number + ": " + afterStr);//325#sdr: 325#sdr
    }

    @Test
    public void test9() {
        String number = "-34327987";
        String afterStr = ConvertUpMoney.toChinese(number);//-34327987: minus thirty-four million three hundred and twenty-seven thousand nine hundred and eighty-seven yuan
        System.out.println(number + ": " + afterStr);
    }

    @Test
    public void test10() {
        String number = "78934029675923532";
        System.out.println("length :" + number.length());//Length: 17
        String afterStr = ConvertUpMoney.toChinese(number);//78934029675923532: beyond computing power
        System.out.println(number + ": " + afterStr);
    }

Process of graphic conversion:

Abbreviated method of converting integer part into RMB capital

Abbreviated method of converting decimal part into RMB capital

Conversion process:

Conversion result:

Two billion three hundred and twenty-seven million eight hundred and ninety-three thousand four hundred and nineteen yuan

Here is a website for capital conversion of RMB amount: http://www.msxindl.com/tools/rmb/

If this article is helpful to you, leave three company ~ ~ thank you!!!

Added by kanuski on Thu, 03 Mar 2022 15:38:32 +0200