Double subtraction precision issue

后端 未结 5 2158
余生分开走
余生分开走 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:38

     //just try to make a quick example to make b to have the same precision as a has, by using BigDecimal
    
     private double getDesiredPrecision(Double a, Double b){
         String[] splitter = a.toString().split("\\.");
         splitter[0].length();   // Before Decimal Count
         int numDecimals = splitter[1].length(); //After Decimal Count
    
         BigDecimal bBigDecimal = new BigDecimal(b);
         bBigDecimal = bBigDecimal.setScale(numDecimals,BigDecimal.ROUND_HALF_EVEN);
    
         return bBigDecimal.doubleValue();  
     }
    

提交回复
热议问题