0
  • While in php, I found 0.58 * 100 = float(58), while intval(0.58 * 100) = int(57).
  • Here is my question (I have learned float-number format IEEE 754.)
    • I guess the number may be stored like 57.999..(cause the int number is 57)
    • but why var_dump(0.58 * 100) display float(58) but float(57.999)?
    • Does php do something else like Rounding or casting?

Here is my code below:

<?php
$dumb=0.58;
var_dump("origin");
var_dump($dumb);
var_dump("float:");
var_dump($dumb*100); 
var_dump("int:");
var_dump(intval($dumb * 100)); //why here is 57 while above float display 58?
die;

This is program result

young
  • 1
  • 4
  • It is impossible to explain quirks like this without a detailed dive into the C++ source code of PHP. Have you looked into that, and what did you find? – KIKO Software Nov 29 '21 at 10:23
  • `ini_set('precision', -1); echo 0.58 * 100;` will tell you why. – Salman A Nov 29 '21 at 10:38
  • thanks @KIKOSoftware, I'll look into the source. And much thanks to Salman A – young Nov 29 '21 at 10:53
  • 1
    @KIKOSoftware: It is certainly not impossible to explain this without a dive into the source code. Using the IEEE-754 binary64 format and arithmetic commonly used for floating-point, the result of `.58*100` is exactly 57.99999999999999289457264239899814128875732421875, which presents as 58 when rounded to fewer than 14 digits after the decimal point and as 57 when truncated to an integer. – Eric Postpischil Nov 29 '21 at 12:18
  • @EricPostpischil: I agree, combining this with the idea that `var_dump()` displays a float with [a precision of 14 significant digits](https://www.php.net/manual/en/ini.list.php) explains it completely. – KIKO Software Nov 29 '21 at 13:17
  • @EricPostpischil thanks very much. I have modify the origin codes with different precisions (<14) (=14) (>14), and I got the results. Now I fully understand, and I know different precision just affect the result "I see", but in fact, the real number stored in the memory is the same value. – young Nov 30 '21 at 06:31

0 Answers0