BigDecimal Error

后端 未结 5 1824
走了就别回头了
走了就别回头了 2021-01-13 01:58

In Java, I have defined k as double k=0.0;

I am taking data from database and adding the same using while loop,

while(rst.         


        
5条回答
  •  误落风尘
    2021-01-13 02:11

    Use BigDecimal.ROUND_HALF_UP (or .._DOWN or .._EVEN).

    Floating point calculations are inherently inaccurate and the small errors accumulate. That's why your end result is off by a small amount. If you always round up, a small positive error like 1.0000000001 becomes 1.01.

    Alternatively you can use BigDecimal also for the calculations. That way you won't have an error in the end result in the first place. Just remember to use the BigDecimal(String) constructor, or obtain the BigDecimal directly from the result set.

提交回复
热议问题