Laravel(或 PHP/MySQL?)削减小数点后的浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48516430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel (or PHP/MySQL?) cuts float numbers after decimal point
提问by Sergej Fomin
Maybe this is a more general MySQL or PHP question deriving from my lack of knowledge in those fields, but...
也许这是一个更一般的 MySQL 或 PHP 问题,因为我缺乏这些领域的知识,但是......
So I have an app on Laravel 5.4, Database is MySQL 5.7.17
所以我在 Laravel 5.4 上有一个应用程序,数据库是 MySQL 5.7.17
I have a column in talbe, created via migration:
我在 talbe 中有一个列,是通过迁移创建的:
$table->float('operator_price', 9, 2)->nullable()->change();
(this, according to Laravel docs, should mean that column has type 'FLOAT' with 9 total digits and 2 after decimal point)
(根据Laravel 文档,这应该意味着该列的类型为“FLOAT”,共有 9 位数字,小数点后为 2 位)
When user enters 1000.25 in the form field and saves - it's saved as '1000.25',
当用户在表单字段中输入 1000.25 并保存时 - 它被保存为“1000.25”,
But if user enters 10000.25 - it's saved as '10000.2'.
但是如果用户输入 10000.25 - 它被保存为“10000.2”。
So it cuts the last digit if the number is over 9999.
所以如果数字超过 9999,它会削减最后一位数字。
What may be the reason and how can I fix it?
可能是什么原因,我该如何解决?
Thank you.
谢谢你。
UPDATE: I've done SHOW COLUMNS FROM tours;
更新:我已经完成了 SHOW COLUMNS FROM tours;
and it shows that column 'operator_price' has type 'float':
它显示“operator_price”列的类型为“float”:
采纳答案by The Alpha
Actually float/double is not as precise as decimal. For monetary data, the decimal type is recommended, so you should probably use:
实际上 float/double 不如十进制精确。对于货币数据,建议使用小数类型,因此您可能应该使用:
$table->decimal(10, 2); // instead of float
Read thisfor some detailed information and float manual from MySql.
回答by aliawadh980
As per Laravel Migration documentation:
根据 Laravel 迁移文档:
$table->float('amount', 8, 2);
FLOAT equivalent column with a precision (total digits) and scale (decimal digits).
具有精度(总位数)和小数位数(小数位数)的 FLOAT 等效列。