• java 四舍五入


    java 对double类型数字进行四舍五入操作

    CreateTime--2017年12月1日10:04:18

    Author:Marydon

    方法一:

    import java.text.DecimalFormat;
    /**
     * 四舍五入
     * 
     * @param number为四舍五入的数字
     * @param keta是保留小数点之后的位数,从0开始
     * @description 0: 表示整数 (155.5->156.0) 1:(0.446->0.4) 2:(0.05 ->0.10) 3:(0.005-0.010)
     */
    public static double rounds(double number, int keta) {
    
        String fmt = "";
        switch (keta) {
        case 0:
            fmt = "#0";
            break;
        case 1:
            fmt = "#0.0";
            break;
        case 2:
            fmt = "#0.00";
            break;
        case 3:
            fmt = "#0.000";
            break;
    
        default:
            fmt = "#0.0000";
            break;
        }
    
        DecimalFormat df = new DecimalFormat(fmt);
    
        return Double.valueOf(df.format(number));// new Double(df.format(number));
    
    }

    方法二:

    /**
     * 提供精确的小数位四舍五入处理。
     * 
     * @param v
     *            需要四舍五入的数字
     * @param scale
     *            小数点后保留几位
     * @return 四舍五入后的结果
     */
    public static double round(double v, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("The scale must be a positive integer or zero");
        }
        BigDecimal b = new BigDecimal(Double.toString(v));
        BigDecimal one = new BigDecimal("1");
        return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    } 

     相关推荐:

  • 相关阅读:
    设计模式(5)>模板方法
    设计模式(2)>工厂方法模式
    分支限界>装载问题
    解决Oracle 11g在用EXP导出时,空表不能导出
    设计模式(7)>观察者模式
    算法>并行算法
    设计模式(15)>桥接模式
    设计模式(9)>迭代器模式
    设计模式(11)>建造者模式
    设计模式(17)>中介者模式
  • 原文地址:https://www.cnblogs.com/Marydon20170307/p/7940646.html
Copyright © 2020-2023  润新知