本文介绍了PHP浮点精度:var_dump是否在秘密地取整,然后如何调试precisley?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

众所周知,PHP中的浮点数不准确( http://php.net/manual/de/language.types.float.php ),但是经过以下实验,我有点不满意:

That floating point numbers in PHP are inaccurate is well known (http://php.net/manual/de/language.types.float.php), however I am a bit unsatisfied after the following experiment:

var_dump((2.30 * 100)); // float(230)
var_dump(round(2.30 * 100)); // float(230)
var_dump(ceil(2.30 * 100)); // float(230)
var_dump(intval(2.30 * 100)); // int(229)
var_dump((int)(2.30 * 100)); // int(229)
var_dump(floor(2.30 * 100)); // float(229)

内部表示形式必须类似于 229.999998 .

The internal representation must be something like 229.999998.

var_dump((2.30 * -100)); // float(-230)
var_dump(round(2.30 * -100)); // float(-230)
var_dump(ceil(2.30 * -100)); // float(-229)
var_dump(intval(2.30 * -100)); // int(-229)
var_dump((int)(2.30 * -100)); // int(-229)
var_dump(floor(2.30 * -100)); // float(-230)

内部表示形式必须类似于 -229.999998 .

The internal representation must be something like -229.999998.

据我所知-整数转换以及intval函数只是简单地切掉了该点后面的所有内容.很高兴知道.

Ok as far as I understand - integer casting as well as the intval function simply cut of everything behind the point. Good to know.

但是 var_dump()给我的值为230,尽管实际值必须根据这些结果而有所不同.

However var_dump() gives me a value of 230 though the real value must be different according to those results.

现在看看这个:

$a = 230.0;

var_dump($a); // float(230)
var_dump((int) $a); // int(230)

这意味着浮点数的内部表示形式在此必须不同.如果我想知道浮点数的确切值,那么我就不能像以前那样使用 var_dump 进行调试了吗?如何调试确切的浮点值?

That means the internal representation of the floating point number must be different here. If I want to know the exact value of a float therefore I can not debug using var_dump as I am used to right? How can I debug an exact float value?

推荐答案

您可以尝试使用数字格式并不是完美的,因为您必须提供小数位数,但应该有所帮助.

You can try to use number_format it won't be perfect since you have to provide number of decimals, but should help.

echo number_format(8-6.4, 50);
echo number_format(2.3*100, 50);

随着小数位数的变化(这也取决于所使用的系统),以下内容可能会有用-确保获得完整的数字并删除尾随的零:

As the number of decimal places is varying (this also depends on the system used) the following might be useful - gets the full number for sure and removes trailing zeros:

echo rtrim(number_format(1.0/3.432, 100),0);

这篇关于PHP浮点精度:var_dump是否在秘密地取整,然后如何调试precisley?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:20