实现四舍五入 String split中含有小数点 str.split(“\\.“)

(如何自己实现和API一样的功能)
public static String round(String str,int digit)
参数1:数字和小数点组成的字符串。如"12.568"
参数2:四舍五入的小数位数。如:2
返回值:根据条件四舍五入后的字符串值。“12.57”
注意:自行编写针对字符串操作的算法,不能使用Java现成的用于四舍五入的API方法

题目已经提示对字符串操作

public static String round(String str, int digit) {
        //1.切割得到split数组,如果长度等于0,返回-1
        String[] split = str.split("\\.");
        String result = null;
        if (split.length == 0) {
            result = "-1";
        }
        String kk = null;
        //2.1 如果切割数组长度=1,加0输出
        if (split.length == 1) {
            for (int i = 0; i < digit; i++) {
                kk += "0";
            }
            //2.2 如果切割长度==2
        } else if (split.length == 2) {
            //2.2.1 小数位长度小于或等于保留位数
            kk = split[1];
            if (split[1].length() <= digit) {
                for (int i = split[1].length(); i < digit; i++) {
                    kk += "0";
                }
                //2.2.2 小数位长度小于或等于保留位数
            } else {
                char[] chars = kk.toCharArray();
                if (chars[digit] < '5') {
                    kk = new String(chars, 0, digit);
                } else {
                    chars[digit - 1] += 1;
                    kk = new String(chars, 0, digit);
                }
            }

        }
        result = split[0] + "." + kk;
        return result;
    }

刚开的是时候返回值一直是“-1”,就是说明split.length==0。后来想到"."是不是需要转义

最后修改成:

String[] split = str.split("\\.");

split.length就正常了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值