简体   繁体   English

PHP浮点精度:var_dump是否秘密舍入,我该如何调试precisley呢?

[英]PHP floating point precision: Is var_dump secretly rounding and how can I debug precisley then?

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: PHP中的浮点数是不准确的是众所周知的( http://php.net/manual/de/language.types.float.php ),但在以下实验后我有点不满意:

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)

The internal representation must be something like 229.999998 . 内部表示必须是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)

The internal representation must be something like -229.999998 . 内部表示必须类似于-229.999998

Ok as far as I understand - integer casting as well as the intval function simply cut of everything behind the point. 好吧据我所知 - 整数转换以及intval函数简单地删除了该点后面的所有内容。 Good to know. 很高兴知道。

However var_dump() gives me a value of 230 though the real value must be different according to those results. 但是var_dump()给出的值为230,尽管实际值必须根据这些结果而不同。

Now have a look at this: 现在来看看这个:

$a = 230.0;

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

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? 如果我想知道浮点数的确切值,那么我无法使用var_dump调试,因为我习惯了吗? 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. 您可以尝试使用number_format它不会是完美的,因为您必须提供小数位数,但应该有所帮助。

echo number_format(8-6.4, 50);

1.59999999999999964472863211994990706443786621093750 1.59999999999999964472863211994990706443786621093750

echo number_format(2.3*100, 50);

229.99999999999997157829056959599256515502929687500000 229.99999999999997157829056959599256515502929687500000

Edit: 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);

0.29137529137529138978379705804400146007537841796875 0.29137529137529138978379705804400146007537841796875

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM