Double subtraction precision issue

后端 未结 5 2157
余生分开走
余生分开走 2020-12-05 04:49

My coworker did this experiment:

public class DoubleDemo {

      public static void main(String[] args) {
           double a = 1.435;
           double b =         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 05:34

    double and float arithmetic are never going to be exactly correct because of the rounding that occurs "under the hood".

    Essentially doubles and floats can have an infinite amount of decimals but in memory they must be represented by some real number of bits. So when you do this decimal arithmetic a rounding procedure occurs and is often off by a very small amount if you take all of the decimals into account.

    As suggested earlier, if you need completely exact values then use BigDecimal which stores its values differently. Here's the API

提交回复
热议问题