Java float unexpectedly rounded

前端 未结 3 388
暖寄归人
暖寄归人 2021-01-17 03:12

I\'m using a float constant and setting a objects private float variable to the float constant below, but when the object outputs the value it was set to, it\'s rounding up

3条回答
  •  不要未来只要你来
    2021-01-17 03:53

    After some testing, I got this result:

    final float RF_FREQUENCY = 956.35625f;
    System.out.println(String.format("%.5f", RF_FREQUENCY));
    final BigDecimal xRF_FREQUENCY = new BigDecimal(956.35625);
    System.out.println(String.format("%.5f", xRF_FREQUENCY));
    

    And the output was:

    956,35626
    956,35625
    

    So, as its explained in more details from coderanch and in this blog post, I recommend you to change to BigDecimal.

    EDIT: I've found another post about same problem in stackoverflow Double vs. BigDecimal? Hope it helps you.

提交回复
热议问题