繁体   English   中英

将双精度转换为2位小数

[英]Convert double to 2 decimal places

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

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

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

输出 -

$15.50

您可以使用BigDecimal格式化:

double value= 255.956666;

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

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

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

在任何地方你需要显示结果显示字符串和计算部分将其转换为Double然后使用它。

您可以使用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));
        }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM