java中四舍五入

1、BigDecimal  

import java.math.BigDecimal;
import static java.math.BigDecimal.ROUND_HALF_DOWN;

public class Test {

    public static void main(String[] args) {

        BigDecimal a = new BigDecimal(11);
        BigDecimal b = new BigDecimal(3);

        BigDecimal divide = a.divide(b, 0, ROUND_HALF_DOWN);
        System.out.println(divide.longValue());

    }
}


//结果:4

 2、Math

float a = 1.6f;

        double b = 2.7d;

        double c = 3.72;

        int round = Math.round(a);
        System.out.println(round);// 2

        long round1 = Math.round(b);
        System.out.println(round1);// 3

        long round2 = Math.round(c);
        System.out.println(round2);// 4


        /**
         * float 必须显式标明f,不然编译器认为是double
         *
         * double 无需显式标明d,编译器默认 会加d
         *
         *          0: ldc           #2                  // float 1.6f
         *          2: fstore_1
         *          3: ldc2_w        #3                  // double 2.7d
         *          6: dstore_2
         *          7: ldc2_w        #5                  // double 3.12d
         *
         */

 

上一篇:Redis实现排行榜(带二位小数点)


下一篇:2021-08-03