0

As shown in the code sample below the conversion of a float value of 43648 to integer with intval() yields int(43647) and not int(43648).

Code:

$f = (float)"43.650" - 0.002;
var_dump($f);
var_dump($f*1000);
var_dump(intval($f*1000));

Output:

float(43.648)
float(43648)
int(43647)

Why?

Michael Kelso
  • 151
  • 1
  • 8
  • To me, `var_dump($f);` outputs `43.647999999999996`, not `43.648`. What version of php are you using? – Cid Dec 05 '22 at 18:06
  • Your `precision` [floating point display precision] setting is clearly set to 5, which I would call "inadvisably low". Float display rounds, but `intval()` does not, it simply drops the fraction. – Sammitch Dec 05 '22 at 19:09
  • @Sammitch Precision is the default 14. – Michael Kelso Dec 06 '22 at 01:20
  • @Cid PHP 7.2.24 – Michael Kelso Dec 06 '22 at 01:21
  • you start with inexact floats/"doubles", then that function truncates; from python shell: print ("%.100f\n" %(43.650)) ==> 43.6499999999999985789145284797996282577514648437500000000000000000000000000000000000000000000000000000; print ("%.100f\n" %(0.002)) ==> 0.0020000000000000000416333634234433702658861875534057617187500000000000000000000000000000000000000000; print ("%.100f\n" %(43.650 - 0.002)) ==> 43.6479999999999961346475174650549888610839843750000000000000000000000000000000000000000000000000000000 – Andrew Dec 12 '22 at 00:09

0 Answers0