mysql浮点类型

时间:2009-06-16 02:50:23

标签: java mysql types

我有一个数据库orderpricedeposit字段设置为浮点类型。我也正在实现一个java gui来搜索订单,问题是当我尝试在数据库中搜索订单时我找不到任何东西,因为当我从string转换为float时它节省了价格= 55.0并且在数据库中它保存为55.问题是什么? 我应该用什么类型来表示来自双方,java方面和mysql方面的货币?

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 ());

2 个答案:

答案 0 :(得分:10)

您是否使用浮点值处理货币?

请不要。

Floating point values不能表示精确的十进制值,因为它们是二进制分数的表示。除非您希望以$ 1.0000000000001之类的值结束,否则请使用整数的数据类型,例如十进制类型。

使用==运算符进行比较无法正常工作的原因是因为许多可以用十进制表示的数字不能用浮点表示,因此,没有完全匹配。

这是一个小例子:

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

输出:

true
200000.48

这两个例子应该表明,依赖货币的浮点值并不是一个好主意。

至于货币值的存储,似乎MySQL中也有DECIMAL类型,所以我认为这是一个更好的选择,除非有一些CURRENCY类型 - - 我对SQL数据库不够熟悉,无法在此提供任何明智的意见。

以下是MySQL 5.1参考手册中的一些信息,Section 10.2: Numeric Types

  

DECIMALNUMERIC数据类型   用于存储精确的数字数据   值。在MySQL中,NUMERIC是   实现为DECIMAL。这些类型   用于存储它的值   保持精确是很重要的   精确度,例如货币   数据

以下是相关问题:

答案 1 :(得分:1)

当您比较浮点数时,您必须始终在小范围内比较它们,比如在处理货币时加上或减半分钱。如果将它们与精确相等进行比较,则总会出现错误,因为浮点并不能精确地表示大多数十进制数。

正是由于这个问题,钱通常作为DECIMAL而不是浮点存储在mySql中。 DECIMAL没有遭受同样的不准确。