在PHP中以字符串形式返回的MySQL小数字段 [英] MySQL decimal fields returned as strings in PHP

查看:145
本文介绍了在PHP中以字符串形式返回的MySQL小数字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,mysqli以字符串形式返回所有值,而MYSQLI_OPT_INT_AND_FLOAT_NATIVE选项允许您将int和float转换为它们的适当类型.尽管这不会影响十进制字段.

By default mysqli returns all values as strings, the MYSQLI_OPT_INT_AND_FLOAT_NATIVE option allows you to convert ints and floats to their appropriate types. Though this does not affect decimal fields.

有没有一种方法可以自动将所有十进制字段转换为php float类型,而无需手动调用$value = (float) $row->some_decimal_field?

Is there a way to automatically cast all decimal fields to a php float type without manually calling $value = (float) $row->some_decimal_field?

推荐答案

我对此表示高度怀疑.小数使用定点数学,PHP中没有可以提供此数据的数据类型.浮点数接近,但实际上是四舍五入的,这意味着将2分配给浮点数可能会导致1.99999999999999999.因此,即使MySQL提供了一种将小数转换为PHP浮点数的方法,您也可能会冒险将数据从小数点转换为浮点数.

I highly doubt it. Decimals use fixed point math, and there is no data type in PHP that can provide this. Floats come close, but they are in fact rounded, meaning that assigning 2 to a float could result in 1.99999999999999999 instead. So even if MySQL offers a way to get a decimal into a PHP float, you are risking loss of data by casting from a decimal to a float.

要清晰地处理此问题,您需要类似 GMP 之类的东西,但是您可能会猜到MySQL无法自动为您提供.您将需要在PHP中手动进行操作.

To handle this cleanly, you'd need something like GMP, but as you can probably guess MySQL can't provide that for you automatically. You will need to do it manually in PHP.

这篇关于在PHP中以字符串形式返回的MySQL小数字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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