title: Java: BigDecimal and inverse formula
body: <p>I am using the following two formulas to calculate upper and lower bounds given an expected result, a deviation and a deviation bound inserted by user:</p>
  
  <pre><code>public static Double getLowerBound(Double deviation,Double expectedValue,Float deviationBound){
      if(deviationBound == null || deviation == null || expectedValue == null)
          return null;
  
      int roundDigit = Math.max(getDecimalFloat(deviation.floatValue()), getDecimalFloat(expectedValue.floatValue()));
      Double valLowerBound = expectedValue - (deviationBound * deviation);
      String valLowerBoundStr = new BigDecimal(valLowerBound).setScale(roundDigit, BigDecimal.ROUND_HALF_UP).toString();
      return Double.valueOf(valLowerBoundStr);
  }
  
  public static Double getUpperBound(Double deviation,Double expectedValue,Float deviationBound){
      if(deviationBound == null || deviation == null || expectedValue == null)
          return null;
  
      int roundDigit = Math.max(getDecimalFloat(deviation), getDecimalFloat(expectedValue));
      Double valUpperBound = expectedValue + (deviationBound * deviation);
      String valUpperBoundStr = new BigDecimal(valUpperBound).setScale(roundDigit, BigDecimal.ROUND_HALF_UP).toString();
      return Double.valueOf(valUpperBoundStr);
  }
  </code></pre>
  
  <p>where method <code>getDecimalFloat()</code> simply parses a float number and returns its digits after comma.
  Then, in another point of my code I have to apply and inverse formula to show deviation bound used before. So I do with:</p>
  
  <pre><code>public static Float getDeviationBound(Double deviation,Double expectedValue,Double lowerBound,Double upperBound){
  
      if(lowerBound == null || upperBound == null || deviation == null || expectedValue == null)
          return null;
  
      String ldb = new BigDecimal(Math.abs((lowerBound-expectedValue)/deviation)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
      String udb = new BigDecimal(Math.abs((upperBound-expectedValue)/deviation)).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
      float lowerDeviationBound = Float.valueOf(ldb);
      float upperDeviationBound = Float.valueOf(udb);
  
      if(lowerDeviationBound == upperDeviationBound)
          return upperDeviationBound;
  
      return null;
  
  }
  </code></pre>
  
  <p>Anyway, for some cases I get NULL back. Why this?
  For example, with a <code>deviationBound = 3.5</code>, <code>expctedValue = 0.43</code>, and <code>lowerBound = 0.045</code> and <code>upperBound = 0.81</code> it is not possible to apply an inverse formula.
  Which way is correct?
  I know that the problem is lowerDeviationBound is different from upperDeviationBound (3.5 vs 3.45) but I don’t know why this happens. Maybe because of some rounding politics of mine, I would like some advice if possible</p>