Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - float number accuracy difference on WAMP and a web server

I am aware that php float numbers are not accurate and I know solutions like BCMath and GMP. I tested the following code on local WAMP server and another server (that uses Nginx):

$size = 0.0006;
$data = json_encode( array("size" => $size));
var_dump($data);

The output on WAMP:

string '{"size":0.0006}' (length=15)

The output on the other server:

string(31) "{"size":0.00059999999999999995}"

PHP version on both servers is 7.3. Why am I getting the expected result on WAMP and something messed up on my hosting server? Is there any configuration that I can fix?

like image 899
MohammadHossein R Avatar asked Jun 17 '26 21:06

MohammadHossein R


1 Answers

Your WAMPs output is not produced by PHP itself but by the Xdebug third-party extension. More specifically:

Xdebug replaces PHP's var_dump() function for displaying variables. Xdebug's version includes different colors for different types and places limits on the amount of array elements/object properties, maximum depth and string lengths.

Apart from that, the precision of implicit string casting of floating values is configurable:

$size = 0.0006;
var_dump($size);
ini_set('precision', 18);
var_dump($size);
float(0.0006)
float(0.000599999999999999947)

In the case of json_encode() the casting is explicit and we can read in the manual:

The encoding is affected by the supplied options and additionally the encoding of float values depends on the value of serialize_precision.

$size = 0.0006;
echo json_encode( array("size" => $size)), PHP_EOL;
ini_set('serialize_precision', 18);
echo json_encode( array("size" => $size)), PHP_EOL;
{"size":0.0006}
{"size":0.000599999999999999947}
like image 95
Álvaro González Avatar answered Jun 20 '26 11:06

Álvaro González



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!