Home > Backend Development > PHP Tutorial > $b=(0.1+0.7)*10; echo intval($b);为何输出0.7?

$b=(0.1+0.7)*10; echo intval($b);为何输出0.7?

WBOY
Release: 2016-06-06 20:38:09
Original
1085 people have browsed it

<code>php</code><code><br><br><br><br><br>  $b=(0.1+0.7)*10;
echo  intval($b);

</code>
Copy after login
Copy after login

为什么输出的是0.7?不是0.8?

回复内容:

<code>php</code><code><br><br><br><br><br>  $b=(0.1+0.7)*10;
echo  intval($b);

</code>
Copy after login
Copy after login

为什么输出的是0.7?不是0.8?

跟浮点数运算的性质有关,你直接输出$b会发现计算的结果是0.7999999,而intval是向下取整的,可以改用ceil。
参见:http://php.net/manual/en/language.types.integer.php#language.types.integer.casting

我们来看一下$b的二进制形式:

<code><?php $b = (0.1 + 0.7) * 10;
$c = unpack('H16hex', pack('d', $b));
echo $c['hex'];
?>
</code>
Copy after login

输出:

<code>ffffffffffff1f40
</code>
Copy after login

由于little-endian, 实际上是 0x401fffffffffffff,这个数字按照IEEE754标准转换为十进制的话 就是

<code>7.999999999999999
</code>
Copy after login

php找不到合适的测试方法,你可以用Java试下以下代码

<code>System.out.println(Double.longBitsToDouble(0x401fffffffffffffL));
</code>
Copy after login

其他的内容, 楼上几位都解释得很清楚了~

http://www.laruence.com/2013/03/26/2884.html

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template