我在数据库中得到一个数据类型为 decimal(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
关于java - 将 double 转换为小数点后两位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17521339/