【问题标题】:round float from microtime来自 microtime 的圆形浮动
【发布时间】:2012-01-20 19:57:32
【问题描述】:

PHP 版本 5.3.6

例子

<?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

这怎么可能?

【问题讨论】:

  • 您通常可以在维基百科上开始研究:en.wikipedia.org/wiki/Floating_point - 但不要相信那里所说的内容。而是遵循书籍建议并阅读接下来的书籍。您也可能对sprintf/fprintf/printf 系列函数感兴趣。

标签: php floating-point floating-accuracy floating-point-precision


【解决方案1】:

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

此外,可以精确表示为以 10 为底的浮点数的有理数,如 0.1 或 0.7,不具有以 2 为底的浮点数的精确表示,无论尾数大小如何,它都在内部使用.因此,它们不能被转换成它们内部的二进制对应物,而不会有小的精度损失。这可能会导致令人困惑的结果:例如, floor((0.1+0.7)*10) 通常会返回 7 而不是预期的 8,因为内部表示将类似于 7.9999999999999991118....

【讨论】:

    猜你喜欢
    • 2012-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    相关资源
    最近更新 更多