2009-06-16 46 views
0

我有一個數據庫orderpricedeposit字段設置爲浮動類型。我也正在實施一個Java gui來搜索訂單,問題是當我嘗試搜索數據庫中的訂單時,我沒有找到任何東西,因爲當我從字符串轉換爲浮點數並將其保存爲數據庫時,它節省了價格= 55.0 55.問題是什麼? 我應該用什麼類型來表示貨幣從雙方,java方面和MySQL方面?mysql float type

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {   
    try{ 
     //collect arguments 
     String category = this.jTextField8.getText(); 
     String pattern=this.jTextArea1.getText(); 
     String color=this.jTextArea2.getText(); 
     float price = Float.valueOf(this.jTextField14.getText()).floatValue(); 
     float deposit = Float.valueOf(this.jTextField15.getText()).floatValue(); 

     //create new order 
     int row=this.customerSelectedRow; 
     Order newOrder=new order(this.customerModel.dataVector.get(row),category,pattern,color,price,deposit); 
     newOrder.search();   
     //refresh 
     this.jDialogNewOrder.setVisible(false); 

    }catch(Exception e){ 
     System.err.println (" Error message: " + e.getMessage()); 
    } 

}      

這裏是關於搜索方法

try { 
       s = c.conn.prepareStatement("SELECT id FROM `"+this.table+ 
         "` WHERE customerId=? AND category=? and pattern=? and color=? and deposit=? and price=?"); 
       s.setInt(1,this.customer.getId()); 
       s.setString (2, this.category); 
       s.setString (3, this.pattern); 
       s.setString (4, this.color); 
       s.setFloat(5,this.deposit); 
       s.setFloat(6,this.price); 
       System.err.println(s.toString()); 
       ResultSet res = s.executeQuery(); 

       System.out.println("printing ids :"); 
       while (res.next()) { 
        int i = res.getInt(1); 
        //assigning the correct id to the inserted customer 
        this.id=i; 
        System.out.println("id" + "=" + i); 
       } 
      } catch (SQLException e) { 
       System.err.println ("find id Error message: " + e.getMessage()); 
       System.err.println ("find id Error number: " + e.getErrorCode()); 

回答

10

你處理貨幣與浮點值的代碼?

請不要。

Floating point values不能表示精確的十進制值,因爲它們是二進制分數的表示。除非您想以$ 1.0000000000001之類的值結尾,否則請使用不可或缺的數據類型,例如十進制類型。

使用==運算符進行比較的原因不能按預期工作是因爲許多可用十進制表示的數字不能用浮點數表示,因此沒有精確匹配。

這裏有一個小例子:

System.out.println(1.00000001f == 1.00000002f); 
System.out.println(200000.99f - 0.50f); 

輸出:

true 
200000.48 

這兩個例子應該表明,依靠浮點值的貨幣不會是一個好主意。

至於貨幣值的存儲,似乎有一種DECIMAL型在MySQL一樣,所以我認爲這將是一個更好的選擇,除非有一些CURRENCY類型 - 我不熟悉不夠用SQL數據庫在這裏給出任何知情的意見。

下面是從MySQL 5.1參考手冊一點點信息,Section 10.2: Numeric Types

DECIMALNUMERIC數據類型是用於存儲精確數值數據 值 。在MySQL中,NUMERIC是 ,實現爲DECIMAL。這些類型 用於存儲其重要的值,以保留精確的 精確度,例如使用貨幣 數據。

這裏有一個相關的問題:

+0

非常好的答案。 :-) – 2009-12-03 15:20:19

1

當您比較浮點數時,您必須始終在小範圍內比較它們,例如在處理貨幣時加上或減去半個便士。如果您將它們與精確相等進行比較,您將始終得到錯誤,因爲浮點不能精確地表示大多數小數。

這是因爲這個問題,錢通常以十進制格式存儲在mySql中,而不是浮點數。 DECIMAL不會遭受相同的不準確。