gpt4 book ai didi

java - mysql浮点型

转载 作者:行者123 更新时间:2023-11-30 23:57:43 25 4
gpt4 key购买 nike

我有一个数据库 orderpricedeposit 字段设置为 float 类型。我也在实现一个 java gui 来搜索订单,问题是当我尝试在数据库中搜索订单时我没有找到任何东西,因为当我从字符串转换为 float 时它保存了 price=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 ());

最佳答案

您正在处理具有浮点值的货币吗?

请不要。

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

之所以使用==运算符进行比较没有达到预期效果,是因为很多可以用十进制表示的数字不能用 float 表示,因此,没有精确匹配。

举个例子:

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 :

The DECIMAL and NUMERIC data types are used to store exact numeric data values. In MySQL, NUMERIC is implemented as DECIMAL. These types are used to store values for which it is important to preserve exact precision, for example with monetary data.

这是一个相关的问题:

关于java - mysql浮点型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/999407/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com