PHP模糊浮点问题 [英] PHP Ambiguous Floating point issue

查看:185
本文介绍了PHP模糊浮点问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在用Laravel 5.0建立一个应用程序,并且在本地(在宅基地内),一切都按预期工作。然而,当我部署项目时,一些问题是明显。其中之一涉及浮动。



Homestead是PHP 5.6,而我的服务器是5.5.9。当我在本地系统上查看价格时,它正确显示为9.99。然而,在我的服务器上,它不能正确显示,而是9.99000。

我的模式有价格字段设置为浮动(12,5),因此额外的权利填充,这也是必需的。

我的问题只是PHP 5.5和5.6(甚至PDO / Eloquent)之间的区别是什么会导致浮点问题解决方案 PHP版本之间没有区别。不同的mysql驱动程序之间有区别,但是,这可能会导致您所看到的问题。



Homestead自带 php5-mysqlnd 已安装,这是MySql本机驱动程序。使用此驱动程序时,从数据库中提取的浮点数和整数将被分配为PHP中的数字数据类型。如果您没有使用本机驱动程序( php5-mysql ),则从数据库中提取的浮点数和整数将被指定为PHP中的字符串。



下面的代码演示了这将如何影响您的输出:

  $ f = 9.99000; 
$ s =9.99000;

echo $ f; //显示9.99
echo $ s; //显示9.99000

您可以检查服务器是否正在使用本地驱动程序,命令 php -i | grep mysqlnd 。这只是通过您的 phpinfo()来查找本地驱动程序的任何提及。如果这不返回任何东西,那么你不使用本地驱动程序,你的数字数据将作为字符串返回。



如果您没有本地驱动程序安装后,你需要删除旧的驱动程序,并安装新的驱动程序:

$ p $ apt-get删除php5-mysql

apt-get install php5-mysqlnd

假设这是您的问题,这将解决它。您也可以查看这个问题和答案以获取更多信息。


I have been building an application with Laravel 5.0 and locally (within homestead) everything works as expected.

However, when I deploy the project a number of issues are apparent. One of which involves floats.

Homestead is PHP 5.6 whilst my server is 5.5.9. When I view a price on my local system it appears correctly as 9.99. However, on my server it does not display correctly but instead as 9.99000.

My schema has price fields set to float(12,5), hence the additional right padding, this is also required.

My question is simply what is the difference between PHP 5.5 and 5.6 (or even PDO/Eloquent) that would cause a floating point issue?

解决方案

There's no difference between the PHP versions that would cause this. There are differences between different mysql drivers, however, and that could cause the issue that you are seeing.

Homestead comes with php5-mysqlnd installed, which is the "MySql Native Driver". When using this driver, floating points and integers fetched from the database will be assigned as numeric datatypes in PHP. If you are not using the native driver (php5-mysql), floating points and integers fetched from the database will be assigned as strings in PHP.

The following code demonstrates how this affects your output:

$f = 9.99000;
$s = "9.99000";

echo $f; // shows 9.99
echo $s; // shows 9.99000

You can check to see if the server is using the native driver with the command php -i | grep mysqlnd. This is just searching through your phpinfo() for any mention of the native driver. If this doesn't return anything, then you are not using the native driver, and your numeric data will be returned as strings.

If you do not have the native driver installed, you will need to remove the old driver and install the new driver:

apt-get remove php5-mysql

apt-get install php5-mysqlnd

Assuming this was your issue in the first place, this will fix it. You can also check out this question and answer for more information.

这篇关于PHP模糊浮点问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆