gpt4 book ai didi

mysql - 如何在mysql中正确使用float类型?

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

我在 mysql 中有一个字段类型为 float(10, 7) 的表。我正在尝试插入值 1196.104,即使在使用 phpmyadmin 时它也会将该值转换为 1000.0000000。我应该使用什么类型来正确地将值 1196.104 存储在数据库中。

最佳答案

这完全按照 FLOAT(10,7) 的预期工作。当您给出的值不适合位数时,它会限制该值并使用可以适合的最大值。

在本例中,10 位数的值 999.9999999 向上舍入为 1000.0000000。

https://dev.mysql.com/doc/refman/8.0/en/floating-point-types.html说:

MySQL permits a nonstandard syntax: FLOAT(M,D) or REAL(M,D) or DOUBLE PRECISION(M,D). Here, (M,D) means than values can be stored with up to M digits in total, of which D digits may be after the decimal point.

换句话说,给了它最大限制为 1000.0000000,因为您告诉它最大为 10 位数字,其中 7 位数字位于小数点右侧。

mysql> create table f ( f float(10,7));

mysql> insert into f values (1196.104);
Query OK, 1 row affected, 1 warning (0.02 sec)

mysql> show warnings;
+---------+------+--------------------------------------------+
| Level | Code | Message |
+---------+------+--------------------------------------------+
| Warning | 1264 | Out of range value for column 'f' at row 1 |
+---------+------+--------------------------------------------+

mysql> select * from f;
+--------------+
| f |
+--------------+
| 1000.0000000 |
+--------------+

如果您想存储更大的值,请声明 FLOAT 并使用足够的数字来保存您使用的值。例如,值 1196.104 可以插入到 FLOAT(11,7)FLOAT(10,6)

或者您可以使用不带参数的 FLOAT,它根本不会限制位数。

关于 FLOAT 有一些注意事项。它是一个不精确的数字类型,并且会有舍入误差。由于 FLOAT 的实现方式,这是不可避免的,它会影响每一种编程语言。

阅读https://dev.mysql.com/doc/refman/8.0/en/problems-with-float.htmlhttps://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

另请参阅我关于此的旧推文: https://twitter.com/billkarwin/status/347561901460447232

enter image description here

关于mysql - 如何在mysql中正确使用float类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51197976/

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