簡體   English   中英

檢索數據,保留小數點后兩位

[英]Retrieve data with 2 decimal place

我在從數據庫中檢索兩位小數的數據時遇到問題。 我正在使用resultset.getDouble()方法。 但這只給我小數點后一位。 我嘗試使用DecimalFormat轉換為2個小數。 運行代碼時,我從DisplayFood.java收到錯誤“字符串無法轉換為雙精度”

DisplayFood.java

Connection connection = null;
Statement statement = null;
ResultSet resultset = null;
DecimalFormat df = new DecimalFormat("#.00");

String query = "SELECT * FROM food";
statement = connection.createStatement();

resultset = statement.executeQuery(query);

while(resultset.next())
{
     FoodRecord foodmenu = new FoodRecord();
     foodmenu.setItemName(resultset.getString("itemName"));

     foodmenu.setPrice(df.format(resultset.getDouble("price")));
     foodmenu.setRestaurant(resultset.getString("restaurant"));

     food.add(foodmenu);
}

FoodRecord.java

public class FoodRecord {
    private String itemName;
    private double price;
    private String restaurant;

    public FoodRecord() {
    }

    public String getItemName() {
        return itemName;
    }

    public void setItemName(String itemName) {
        this.itemName = itemName;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getRestaurant() {
        return restaurant;
    }

    public void setRestaurant(String restaurant) {
        this.restaurant = restaurant;
    }

}

您收到此錯誤的原因是,您試圖在雙精度字段中設置字符串值。 使用resultset.getDouble("price")從結果集中讀取價格。

要使用兩個小數位打印價格,可以將格式化程序與System.out.println一起使用,例如df.format(foodMenu.getPrice())

我正在使用resultset.getDouble()方法。 但這只給我小數點后一位

getDouble()方法以java中表示的double形式返回值數字。

getDouble() javadoc:

以Java編程語言中double的形式檢索此ResultSet對象的當前行中指定列的值。

這意味着如果您的數字值為10.5 ,則雙10.50值將為10.5而不是10.50

我嘗試使用DecimalFormat轉換為2位小數

DecimalFormat.format(double number)將double格式化為具有特定格式的String
指定的格式在您的代碼中:

DecimalFormat df = new DecimalFormat("#.00");

因此,是的,您不能將Double分配給String因為它們是不兼容的類型。
為了解決您的問題,您必須將DecimalFormat.format(double number)的結果存儲在String

但這確實與FoodRecord類不一致,在FoodRecord類中, price是一個double字段: private double price;

在類中將pricedouble更改為String不一定是最好的方法,原因有兩個:

  • 數據的視覺表示不應更改數據值。 如果小數點為4浮點值(例如: 10.5445 ),則將其格式化為10.54並將信息僅作為String字段存儲在類中會截斷數據值。 如果再次將值存儲在數據庫中,則它將更改初始值,而客戶端未修改對象。

  • 你不能不再有一個簡單的setPrice()方法有雙(所以以自然的方式),你應該在執行一些計算setPrice()方法的改變double到一個String

為了解決您的問題,您可以引入一種返回格式化價格的新方法:

public String getFormatedPrice(){
  return df.format(resultset.getDouble("price"));
}

如果經常調用getFormatedPrice() ,則可以緩存結果,而不是調用df.format()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM