Android - exact mathematical calculation

前端 未结 4 830
忘了有多久
忘了有多久 2021-01-26 10:26

I have got a Problem, I am developing an Application which should be able to do some mathematic calculations. These calculations have to be exact (or rather not obviously wrong)

相关标签:
4条回答
  • 2021-01-26 10:41

    This is a consequence of the IEEE 754 floating point representation, not an error. To deal with it, round your result to an appropriate precision.

    0 讨论(0)
  • 2021-01-26 10:42

    Use a BigDecimal for precise floating point calculations. Setting the scale allows you to specify precisely how far out you want to go for output.

    import java.math.BigDecimal;
    
    class Test{
    
            public static void main(String[] args){
                    BigDecimal a = new BigDecimal("3.048");
                    BigDecimal b = new BigDecimal(1000);
                    BigDecimal c = a.divide(b).setScale(6);
                    System.out.println(c); //0.003048
            }
    }
    
    0 讨论(0)
  • 2021-01-26 10:45

    Use BigDecimal for such precise allocations.

    Btw the result for d is obviously right, because double has a machine encoding which cannot store the result, which you perceive as correct.

    0 讨论(0)
  • 2021-01-26 10:51

    What you need to use for exact percision is the BigDecimal object:

    BigDecimal a = new BigDecimal("3.048");
    BigDecimal b = new BigDecimal(1000);
    
    BigDecimal c = a.divide(b);
    
    System.out.println(c); //0.003048
    
    0 讨论(0)
提交回复
热议问题