Can't put Double number in BigDecimal variable

2019-03-05 02:40发布

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 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.

 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

2条回答
不美不萌又怎样
2楼-- · 2019-03-05 03:03

This program illustrates conversion in both directions between Double and 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.

查看更多
地球回转人心会变
3楼-- · 2019-03-05 03:03

Obviously priceSpinner.getValue() returns BigDecimal and you're trying to convert it to double and then back to BigDecimal.

Why don't you just do?

insertStmt.setBigDecimal(position, (BigDecimal) priceSpinner.getValue());
查看更多
登录 后发表回答