0

I need to divide a financial value, sum the values and after this check if they are the same. Something like:

BigDecimal a = new BigDecimal(45.58);
List<BigDecimal> lista = new ArrayList<BigDecimal>();
BigDecimal sum = new BigDecimal("0");

for(int i=0;i<31;i++){
   lista.add(a.divide(new BigDecimal(31), 6, RoundingMode.HALF_UP));
   sum = sum.add(lista.get(i));
   System.out.println(lista.get(i));
}

System.out.println("Initial value:   "+a);
System.out.println("Total: "+sum);

The issue is that when I do this I can't get the same value. If I use 45.58(could be any value) for example I get:

Initial value:   45.5799999999999982946974341757595539093017578125
Total:           45.580013

How can I get something like(The important thing is that the variables "sum" and "a" be the same):

Initial value:   45.580013
Total:           45.580013

Thanks all in advanced!

  • Do you have to use BigDecimal? – LostAvatar Oct 21 '13 at 13:37
  • To create a `BigDecimal` from a `double` value, in this case you should use the `BigDecimal.valueOf(double)` method instead of the `BigDecimal(double)` constructor. See [this question and answer](http://stackoverflow.com/q/460755/658907). – matts Nov 11 '13 at 23:39
  • You can use http://jscience.org/api/index.html?overview-summary.html API – LMK May 15 '14 at 13:29

0 Answers0