I just cannot find the correct answer, so here is my problem: I want to be able to calculate the indexation (a positive or negative percentage) over a price
and period
.
Expectations:
Case #1
Price : 1.000,00
Indexation percentage : 5%
Calculation over 5 years with positive percentage:
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
Case #2
Price : 1.000,00
Indexation percentage : -5%
Calculation over 5 years with negative percentage:
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
Results:
And this negative percentage goes wrong, because my java code prints this out:
1000
-5000
-125000
15625000
1175690408
My code is pretty simple, i think:
BigDecimal percentageValue = new BigDecimal("-5");
BigDecimal indexation = percentageValue.divide(ONE_HUNDRED).add(BigDecimal.ONE);
BigDecimal price = new BigDecimal("1000");
for (int i = 0; i < 5; i++)
{
price = price.multiply(indexation.pow(i));
System.out.println(price.intValue());
}
Solution:
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 < 5; i++)
{
BigDecimal result = price.multiply(indexation.pow(i));
System.out.println(result);
}
}