保留小数点后的数字不用四舍五入有知道例子的吗?

现在的结果

46.017700

我想要达到的结果

46.017700
将后面的0给去掉
要是
46.017717
就不用去掉数字

如果是六个0就保留小数点后两位
0.000000
改成
0.00

package cn.hutool.core.util

https://hutool.cn/docs/#/core/%E5%B7%A5%E5%85%B7%E7%B1%BB/%E6%95%B0%E5%AD%97%E5%B7%A5%E5%85%B7-NumberUtil

NumberUtil.找下你要的

用字符串的方式去判断处理吧。

默认6位小数


import java.text.DecimalFormat;

public class Test2 {
    public static void main(String[] args) {
        Double number = 46.017700;       //这里修改数字
        DecimalFormat dd = new DecimalFormat("#.000000");
        String result = dd.format(number);
        int d = getIndex(result);
        System.out.println(deleteString(result,d));
    }

    public static int getIndex(String s){
        int index = 999;

        for (int i = s.length()-1; i > 0; i--) {
            String lastNum = String.valueOf(s.charAt(i)); //从末尾开始
            if (lastNum.equals("0")){ //末尾为0
                index = Math.min(index,i);  //记录最小index
            }else if (lastNum.equals(".")){  //6位全是0
                    return -1;
            }else if (!lastNum.equals("0")) {
                return index;
            }
        }
        return index;
    }

    public static String deleteString(String str, int index ){
        if (index == 999){
            return str;
        }
        if (index == -1){
            double result = Double.parseDouble(str);
            return new DecimalFormat("#.00").format(result);
        }
        String delStr = "";
        for (int i = 0; i < str.length(); i++) {
            if(i != index){
                delStr += str.charAt(i);
            }
            else break;
        }
        return delStr;
    }
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632