2

PHP Version 5.3.6

Example

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

File round.txt contains these lines:

131.3048491477966 = 131.3

8.340715885162354 = 8.34

8.198318004608154 = 8.199999999999999

how is that possible?

hakre
  • 193,403
  • 52
  • 435
  • 836
Sergey L
  • 547
  • 2
  • 5
  • 19
  • You can most often start research on wikipedia: http://en.wikipedia.org/wiki/Floating_point - but do not believe what is told there. Instead follow the book-suggestions and read the books next. Also you might be interested in the `sprintf`/`fprintf`/`printf` family of functions. – hakre Jul 24 '12 at 11:17

1 Answers1

3

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

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....

ceejayoz
  • 176,543
  • 40
  • 303
  • 368