Java 分数转小数、百分数转小数

文章介绍了如何使用Java编程语言将分数和百分数转换为小数,涉及`fractionToDecimal`和`percentageToDecimal`方法,以及`isPercentage`方法用于判断输入是否为百分数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


    /**
     * 分数转小数
     *
     * @param str
     * @return
     */
    public static BigDecimal fractionToDecimal(String str) {
        Integer numerator = Integer.valueOf(str.substring(0,str.lastIndexOf("/")));
        Integer denominator = Integer.valueOf(str.substring(str.lastIndexOf("/") + 1));
        long x = numerator,y = denominator;
        if(x % y == 0) return new BigDecimal("" + x / y);
        String res = "";
        // 如果同号则为0,不同则为1,加上一个负号
        if((x < 0) ^ (y < 0)) res += '-';
        x = Math.abs(x);
        y = Math.abs(y);
        // 记录商
        res += x / y + ".";
        // x此时表示余数
        x %= y;
        // 用哈希表记录所有出现过的余数
        Map<Long,Integer> hashmap = new HashMap<>();
        // x == 0表示除尽了
        while(x != 0){
            // 记录当前余数对应的商是多少位
            hashmap.put(x,res.length());
            x *= 10; // 余数每次要乘10再进行除法操作 ---  模拟除法
            res += x / y;
            x %= y;
            // 如果出现了重复的余数
            if(hashmap.containsKey(x)){
                res = res.substring(0,hashmap.get(x)) + "" + res.substring(hashmap.get(x));
                break;
            }
        }
        return new BigDecimal(res);
    }

    /**
     * 百分数转为小数
     * @param str
     * @return
     */
    public static BigDecimal PercentageToDecimal(String str) {
        BigDecimal decimal;
        NumberFormat nf=NumberFormat.getPercentInstance();
        try {
            decimal = new BigDecimal(nf.parse(str).toString());
        } catch (ParseException e) {
            throw new DataException("百分数转换异常");
        }
        return decimal;
    }


    /**
     * 是否为百分数
     * @param str
     * @return
     */
    public static Boolean isPercentage(String str){
        if (StringHelperDomain.isEmpty(str)){
            return false;
        }
        return str.endsWith("%");
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值