1

我在数据库中有一个十进制(18,2)数据类型的表列作为价格。当我创建一个产品时,假设我输入了 15.50 美元,它在数据库中存储为 15.50。但是,当我尝试将数据库中的值作为 Double 检索并显示在表中时,它显示 15.5。这就是我在表格中设置价格的方式:

 TableColumn prodPriceCol = new TableColumn("PRICE ($)");
 prodPriceCol.setCellValueFactory(new PropertyValueFactory<Product, Double>("prodPrice"));
 prodPriceCol.setMinWidth(100);

然后在我的产品类中:

private SimpleDoubleProperty prodPrice;

 public void setprodPrice(double value) {
    prodPriceProperty().set(value);
}

public Double getprodPrice() {
    return prodPriceProperty().get();
}

public SimpleDoubleProperty prodPriceProperty() {
    if (prodPrice == null) {
        prodPrice = new SimpleDoubleProperty(this, "prodPrice");
    }
    return prodPrice;
}

还有我的 SQL:

String sql = "SELECT * FROM sm_product WHERE productCategory = '" + category + "'";
        ResultSet rs = null;
        // Call readRequest to get the result
        rs = db.readRequest(sql);

        while (rs.next()) {
            String ID = rs.getString("productID");
            String name = rs.getString("productName");
            String desc = rs.getString("productDescription");
            double price = rs.getDouble("productPrice");

顺便说一句,我是在 JavaFX 中做的。

4

5 回答 5

3

使用 . 将您的双精度值格式化为格式化字符串DecimalFormat

String priceString = new DecimalFormat("$##.##").format(price);

输出-

$15.50
于 2013-07-08T07:44:05.150 回答
2

您可以使用以下格式进行格式化BigDecimal

double value= 255.956666;

BigDecimal bd = new BigDecimal(value).setScale(2, RoundingMode.HALF_UP);
System.out.println("value=" + bd);
于 2015-05-27T17:57:20.310 回答
0

我建议,以字符串的形式获取值。

String price = rs.getString("productPrice");

并且无论您需要在哪里显示结果,都显示字符串,并在计算部分将其转换为 Double 然后使用它。

于 2013-07-08T07:45:32.543 回答
0

您可以使用 NumberFormat 格式化价格:

  NumberFormat nf = new NumberFormat() ;
    nf.setMaximumFractionDigits(2) 
    nf.setMinimumFractionDigits(2)  


        nf.format(ton_double)
         while (rs.next()) {
                    String ID = rs.getString("productID");
                    String name = rs.getString("productName");
                    String desc = rs.getString("productDescription");
            double priceNF = rs.getDouble("productPrice");

                    double price = Double.valueOf(nf.format(priceNf));
        }
于 2013-07-08T07:58:00.303 回答
0

您不应该将您的值存储为Doubles。BigDecimal是货币价值的标准类型。

于 2013-07-08T08:21:25.060 回答