Java float 123.129456 to 123.12 without rounding

后端 未结 5 2090
一个人的身影
一个人的身影 2020-12-20 16:11

How do you cut down float primitive in java to two decimal places, without using rounding?:

123.99999 to 123.99
-8.022222 to         


        
5条回答
  •  春和景丽
    2020-12-20 16:43

    Do keep in mind that float are floating point values. So there might not even be an exact two decimal representation for a certain number.

    Having said that, you might try something like:

    float f = -8.022222f;
    BigDecimal bd = new BigDecimal(f);
    BigDecimal res = bd.setScale(2, RoundingMode.HALF_UP);
    f = res.floatValue();
    System.out.println(f);
    

    You might need to use a different RoundingMode though. Depends on what you want.

提交回复
热议问题