BigDecimal错误 [英] BigDecimal Error
问题描述
在Java中,我将k定义为
double k = 0.0;
从数据库获取数据,并使用同时使用
循环添加相同的数据,
while (rst.next()){
k = k + Double.parseDouble(rst.getString(5));
}
注意:在数据库中,我的值为125.23 ,458.45,665.99(所有两个小数)
当我显示k时,我获得价值作为
k = 6034.299999999992
所以我介绍了 BigDecimal
并将代码更改为
BigDecimal bd = new BigDecimal(k);
bd = bd.setScale(2,BigDecimal.ROUND_UP);
现在我得到新的总额为$ code> bd = 6034.30 这是正确的。
问题1
问题是当我在其他地方使用相同,下面是我得到的
k = 157.3
bd = 157.31
应该在手动添加后显示 bd = 157.30
我得到 157.30
。
任何为什么它显示为 157.31
。
问题2
这么多小数值?
下面是不同的值我得到双变量k
157.3
67.09
1014.6000000000003
229.06999999999996
我不明白有时会显示一个小数,有时它显示2个小数大部分时间都显示14个十进制值。
任何建议将不胜感激。
您仍然通过 双重
进入。坚持 BigDecimal
无处不在:
BigDecimal k = BigDecimal.ZERO;
/ pre>
while(rst.next()){
k = k.add(new BigDecimal(rst.getString(5));
}
或者 - 最好是如果数据库中的字段实际上是一个十进制值:
BigDecimal k = BigDecimal.ZERO;
while(rst.next()){
k = k.add(rst.getBigDecimal(5));
}
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 belowBigDecimal 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 get157.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.
解决方案You're still going via
double
. Stick toBigDecimal
everywhere:BigDecimal k = BigDecimal.ZERO; while (rst.next()) { k = k.add(new BigDecimal(rst.getString(5)); }
Alternatively - and preferrably, if the field in the database is actually a decimal value:
BigDecimal k = BigDecimal.ZERO; while (rst.next()) { k = k.add(rst.getBigDecimal(5)); }
这篇关于BigDecimal错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!