In Java, I have defined k as
double k=0.0;
I am taking data from database and adding the same using while
loop,
while(rst.next()) {
k = k + Double.parseDouble(rst.getString(5));
}
NOTE: In database, I have values as 125.23, 458.45, 665.99 (all two decimals)
When I display k, I get value as
k = 6034.299999999992
Hence I introduced BigDecimal
and changed code to below
BigDecimal bd = new BigDecimal(k);
bd = bd.setScale(2,BigDecimal.ROUND_UP);
Now I get new total as bd=6034.30
which is correct.
Problem 1
Well the problem is when I am using same at other place, below is what I am getting
k = 157.3
bd = 157.31
It should have shown bd=157.30
as after adding manually I get 157.30
.
Any reason why it is showing as 157.31
.
Problem 2
Also any reason why k is showing so many decimal values? Below are different values I am getting for double variable k
157.3
67.09
1014.6000000000003
229.06999999999996
I don't understand sometime it displays one decimal, sometime it display 2 decimal and most of the time it show 14 decimal value.
Any suggestion would be appreciated.