Rounding with DecimalFormat in Java

后端 未结 2 1849
感动是毒
感动是毒 2021-01-11 14:17

Let\'s look at the following statements in Java.

System.out.println(new DecimalFormat(\"0\").format(2.4)); //returns 2

System.out.println(new DecimalFormat(         


        
2条回答
  •  悲&欢浪女
    2021-01-11 15:20

    The default rounding mode of DecimalFormat is RoundingMode.HALF_EVEN. This means that it rounds up, or rounds down if the number is nearer to the next neighbour. When the number is exactly between two neighbours (in your case, 2 and 3), it rounds to the nearest even number (in your case, 2).

    As you can see, when you tried it with 3.5, it rounded to 4.

    If you want the more "intuitive" behaviour, call setRoundingMode(RoundingMode.HALF_UP) http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html#setRoundingMode(java.math.RoundingMode)

    this is the same as HALF_EVEN, but if the number is exactly between two neighbours, will always round upwards.

提交回复
热议问题