Note that there are some explanatory texts on larger screens.

plurals
  1. POBigDecimal.pow() of negative number
    text
    copied!<p>I just cannot find the correct answer, so here is my problem: I want to be able to calculate the indexation (<em>a positive or negative percentage</em>) over a <code>price</code> and <code>period</code>.</p> <p><strong>Expectations:</strong></p> <hr> <p><strong>Case #1</strong><br> Price : <strong>1.000,00</strong><br> Indexation percentage : <strong>5%</strong> </p> <p>Calculation over 5 years with positive percentage:</p> <pre><code>1. 1000 x 5^0 = 1000 2. 1000 x 5^1 = 1050 3. 1000 x 5^2 = 1102,50 4. 1000 x 5^3 = 1157.625 5. 1000 x 5^4 = 1215,50625 </code></pre> <p><strong>Case #2</strong><br> Price : <strong>1.000,00</strong><br> Indexation percentage : <strong>-5%</strong> </p> <p>Calculation over 5 years with negative percentage:</p> <pre><code>1. 1000 x -5^0 = 1000 2. 1000 x -5^1 = 950 3. 1000 x -5^2 = 902,50 4. 1000 x -5^3 = 857,375 5. 1000 x -5^4 = 814,50625 </code></pre> <p><strong>Results:</strong></p> <hr> <p>And this negative percentage goes wrong, because my java code prints this out:</p> <pre><code>1000 -5000 -125000 15625000 1175690408 </code></pre> <p>My code is pretty simple, i think:</p> <pre><code>BigDecimal percentageValue = new BigDecimal("-5"); BigDecimal indexation = percentageValue.divide(ONE_HUNDRED).add(BigDecimal.ONE); BigDecimal price = new BigDecimal("1000"); for (int i = 0; i &lt; 5; i++) { price = price.multiply(indexation.pow(i)); System.out.println(price.intValue()); } </code></pre> <p><strong>Solution:</strong></p> <pre><code>static final BigDecimal ONE_HUNDRED = new BigDecimal("100"); public static void main(String[] args) { BigDecimal percentageValue = new BigDecimal("-5"); BigDecimal indexation = percentageValue.divide(ONE_HUNDRED).add(BigDecimal.ONE); BigDecimal price = new BigDecimal("1000"); for (int i = 0; i &lt; 5; i++) { BigDecimal result = price.multiply(indexation.pow(i)); System.out.println(result); } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload