Java小案例----金额的中文表达

        当我们去查看支票上的数字或着账单上的数字时,会发现它们都是用中文来表达数字的,那么此时的需求就是将用户输入的阿拉伯数字转换为中文表达的形式(不得超过9999999),而且如果在该单位上没有数值的统一写成零,样品如下:

666

转化后如下
零佰零拾零万零仟陆佰陆拾陆元

具体实现如下:

1:可以将传入的阿拉伯数字转为对应的中文表达

 public static String moneyChange(int num){
        String[]arr = new String[]{"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
        return arr[num];
    }

 2.将转换后的数据进行拼接并加以单位修饰

public static String Css(String result){
        String newResult = "";
        String[]arr = new String[]{"元","拾","佰","仟","万","拾","佰"};
        int j = arr.length - 1;
        for (int i = 0; i < arr.length; i++) {
//判断是否在该位上有数据,没有则补零
            if(i == arr.length - result.length())
                break;
            newResult = newResult + '零' + arr[j--];
        }
        for (int i = 0; i < result.length(); i++) {
            newResult = newResult + result.charAt(i) + arr[j--];
        }
        return newResult;
    }

完整代码如下:

import java.util.Scanner;
public class changeMoney {
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        System.out.println("请输入你需要转换的金额");
        int num = sc.nextInt();
        int ge = 0;
        String result = "";
        if(num>=0 && num<=9999999){
            while(num>0){
                ge = num % 10;
                num /= 10;
                result = moneyChange(ge) + result;
            }
            result = Css(result);
            System.out.println(result);
        }
    }
    public static String moneyChange(int num){
        String[]arr = new String[]{"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
        return arr[num];
    }
    public static String Css(String result){
        String newResult = "";
        String[]arr = new String[]{"元","拾","佰","仟","万","拾","佰"};
        int j = arr.length - 1;
        for (int i = 0; i < arr.length; i++) {
            if(i == arr.length - result.length())
                break;
            newResult = newResult + '零' + arr[j--];
        }
        for (int i = 0; i < result.length(); i++) {
            newResult = newResult + result.charAt(i) + arr[j--];
        }
        return newResult;
    }
}

效果图如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值