Java 不能在 BigDecimal 变量中放入双精度数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27780642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't put Double number in BigDecimal variable
提问by abdou amer
I'm using a Double variable which holds the Item price. That variable is stored in postgresql database under a column of money type. I use setBigDecimal(position,value) SQL function.In other part, i'm using a JSpinner as input.
我正在使用一个保存商品价格的 Double 变量。该变量存储在 postgresql 数据库中的货币类型列下。我使用 setBigDecimal(position,value) SQL 函数。在其他部分,我使用 JSpinner 作为输入。
Double current = 0.0;
Double min = (double) Integer.MIN_VALUE;
Double max = (double) Integer.MAX_VALUE;
Double step = 0.1;
JSpinner priceSpinner = new JSpinner(new SpinnerNumberModel(current, min, max, step));
When the user clicks on a button, I get the value entred by the user and put it in the database via SQL query.
当用户单击按钮时,我会获取用户输入的值并通过 SQL 查询将其放入数据库中。
insertStmt.setBigDecimal(position,BigDecimal.valueOf((double) priceSpinner.getValue()));
But, i got this little error,
但是,我得到了这个小错误,
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.math.BigDecimal cannot be cast to java.lang.Double
采纳答案by Patricia Shanahan
This program illustrates conversion in both directions between Double and BigDecimal:
该程序说明了 Double 和 BigDecimal 之间的双向转换:
import java.math.BigDecimal;
public class Test {
public static void main(String[] args) {
Double d1 = 1.3;
BigDecimal bd1 = BigDecimal.valueOf(d1.doubleValue());
Double d2 = bd1.doubleValue();
System.out.println(d2);
}
}
Note that the conversion to Double may not be exact.
请注意,转换为 Double 可能不准确。
回答by Konstantin Yovkov
Obviously priceSpinner.getValue()
returns BigDecimal
and you're trying to convert it to double
and then back to BigDecimal
.
显然priceSpinner.getValue()
返回BigDecimal
,您正在尝试将其转换double
为BigDecimal
.
Why don't you just do?
你为什么不做?
insertStmt.setBigDecimal(position, (BigDecimal) priceSpinner.getValue());