将双精度转换为2位小数

时间:2013-07-08 07:42:06

标签: java

我在数据库中有一个带有十进制(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中这样做。

5 个答案:

答案 0 :(得分:3)

使用DecimalFormat将双值格式化为格式化字符串。

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

输出 -

$15.50

答案 1 :(得分:0)

我建议,以String的形式获取值。

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

无论你需要显示结果显示字符串,计算部分将其转换为Double然后再使用它。

答案 2 :(得分: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));
        }

答案 3 :(得分:0)

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

答案 4 :(得分:0)

您可以使用BigDecimal

进行格式化
double value= 255.956666;

BigDecimal bd = new BigDecimal(value).setScale(2, RoundingMode.HALF_UP);
System.out.println("value=" + bd);