2

PHP版本5.3.6輪浮子從microtime中

<?php 
$timeStart = microtime(true); 
// some code ...  
$timeExecution = microtime(true) - $timeStart; 
$time = round($timeExecution, 2); 
file_put_contents('h:/round.txt', $timeExecution . ' = ' . $time . "\n", FILE_APPEND); 
?> 

文件round.txt包含這些行:

131.3048491477966 = 131.3

8.340715885162354 = 8.34

8.198318004608154 = 8.199999999999999

這怎麼可能?

+0

你可以最經常開始研究維基百科:http://en.wikipedia.org/wiki/Floating_point - 但不要相信那裏有什麼。相反,請按照本書的建議閱讀下一本書。你也可能對'sprintf' /'fprintf' /'printf'函數族感興趣。 – hakre

回答

3

http://php.net/manual/en/language.types.float.php

此外,有理數是作爲浮點數在基座10,如0.1或0.7精確表示,沒有一個確切表示作爲浮點數在基座2,其是在內部使用,不管尾數的大小。因此,他們不能被轉換成其內部的二進制對應,而不會有小的精度損失。這可能導致混亂的結果:例如,地板((0.1 + 0.7)* 10)通常會返回7而不是預期8中,由於內部表示將會像7.9999999999999991118 ....