I have an issue with some calculations inside my app. It is basically some kind of shopping list app. The user inputs the quantity and the price. There can be as much as 150 products in that list but usually it's something like 20,on average.
I'm using JTextFields
,getting the Strings
out of them and putting them into Arrays
.I'm then parsing the Double and doing my calculations.
The issue is that I sometimes get a total from the user in my database and when i verify it its wrong,for example(the shortest list i could find that has the error):
10 * 27.10
10 * 27.81
Total: 549.08
Clearly,the total is not 549.08
but 549.1
.
Now,I know my method for the calculation is not the best,I did it a couple of months ago when I knew very little about Java and I left it like that since it did the job and I don't have calculations that are very complicated. So I didn't move to BigDecimal since I do this calculation a lot and from what I've read,it's a lot slower then double and float.
Anyway,here's my method:
Double totaltest=0;
for (int j = 0; j < allcant.size(); j++) {
cant[j] = allcant.get(j).getText().toString();
pret[j] = allpret.get(j).getText().toString();
Double temp = Double.parseDouble(cant[j]) * Double.parseDouble(pret[j]);
totaltest = totaltest + temp;
}
Could the issue come out of here? Or should I look somewhere else in my code? I'll most probably change the way I do the calculations anyway but I'd like to know what's the best way to do it and if I made a mistake here. I now know about floating point and stuff but the weird part is that it gives the right total when I try to replicate it.