从MySQL文档http://dev.mysql.com/doc/refman/5.1/en/problems-with-float.html示例(ⅰ其缩小,此节文档是5.5相同)
mysql> create table t1 (i int, d1 double, d2 double);
mysql> insert into t1 values (2, 0.00 , 0.00),
(2, -13.20, 0.00),
(2, 59.60 , 46.40),
(2, 30.40 , 30.40);
mysql> select
i,
sum(d1) as a,
sum(d2) as b
from
t1
group by
i
having a <> b; -- a != b
+------+-------------------+------+
| i | a | b |
+------+-------------------+------+
| 2 | 76.80000000000001 | 76.8 |
+------+-------------------+------+
1 row in set (0.00 sec)
基本上如果你总结一个你0-13.2 + 59.6 + 30.4 = 76.8。如果我们总结b,我们得到0 + 0 + 46.4 + 30.4 = 76.8。 a和b的总和相同,但MySQL文档中提到:
写入SQL语句中的浮点值可能与内部表示的值不同。
如果我们重复相同的十进制:
mysql> create table t2 (i int, d1 decimal(60,30), d2 decimal(60,30));
Query OK, 0 rows affected (0.09 sec)
mysql> insert into t2 values (2, 0.00 , 0.00),
(2, -13.20, 0.00),
(2, 59.60 , 46.40),
(2, 30.40 , 30.40);
Query OK, 4 rows affected (0.07 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> select
i,
sum(d1) as a,
sum(d2) as b
from
t2
group by
i
having a <> b;
Empty set (0.00 sec)
预期的结果是空集。
所以只要你不执行,你可以使用双任何SQL arithemetic操作,但我还是喜欢十进制数。
如果小数部分太大,还需要注意关于DECIMAL的另一件事。例如:
mysql> create table t3 (d decimal(5,2));
Query OK, 0 rows affected (0.07 sec)
mysql> insert into t3 (d) values(34.432);
Query OK, 1 row affected, 1 warning (0.10 sec)
mysql> show warnings;
+-------+------+----------------------------------------+
| Level | Code | Message |
+-------+------+----------------------------------------+
| Note | 1265 | Data truncated for column 'd' at row 1 |
+-------+------+----------------------------------------+
1 row in set (0.00 sec)
mysql> select * from t3;
+-------+
| d |
+-------+
| 34.43 |
+-------+
1 row in set (0.00 sec)
您是否使用Java计算应税金额,然后根据合同对它们进行四舍五入,然后再存储它们?例如,如果您销售的产品价格为1.47美元,并且拥有8.25%的本地销售税,则您可能需要记录税金0.121275美元。我想知道你以什么形式在数据库中存储这种类型的字段,以及在你存储之前是否舍入到0.12美元(或取决于你的语言环境,达到0.13美元)。 – rajah9
是的,我们计算税额在Java中,我们存储项目的价格,四舍五入至小数点第四和总价四舍五入至小数点第2税额。所以在你的例子中,一行将包含 1.47,0.1213和1.59。 8.25%存储在其他地方为0.08250000,不会为每次销售重复。 – user327961