Round a double in Java

前端 未结 6 1086
余生分开走
余生分开走 2020-12-08 00:31

I have found this great solution for rounding:

static Double round(Double d, int precise) {
    BigDecimal bigDecimal = new BigDecimal(d);
    bigDecimal = b         


        
6条回答
  •  猫巷女王i
    2020-12-08 00:52

    You have to replace

    BigDecimal bigDecimal = new BigDecimal(d);
    

    with

    BigDecimal bigDecimal = BigDecimal.valueOf(d);
    

    and you will get the expected results:

    2.66
    1.66
    

    Explanation from Java API:

    BigDecimal.valueOf(double val) - uses the double's canonical string representation provided by the Double.toString() method. This is preferred way to convert a double (or float) into a BigDecimal.

    new BigDecimal(double val) - uses the exact decimal representation of the double's binary floating-point value and thus results of this constructor can be somewhat unpredictable.

提交回复
热议问题