0

As the title says, when I place an array into http_build_query() all the float types end up with lost precision. For instance:

$arr = ['test' => 22854.94878205978 ];
print_r($arr);                   // prints 22854.94878205978
print_r(http_build_query($arr)); // prints 22854.94878206

I'm unsure why. I can't find anything in the PHP docs that would cause this. My main focus is just sending some data via a POST request using cURL via PHP, ie.

$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"POST");
curl_setopt($ch,CURLOPT_POSTFIELDS, http_build_query($arr));
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
$result = curl_exec($ch);

Since I need the precision, what can I do and why is this happening?

Alex
  • 2,145
  • 6
  • 36
  • 72

1 Answers1

0

You have three options

  • Use string to hold float number.
  • Set more precision via ini_set('precision', <precision>);.
  • And you can split float into two integer parts.

Be aware, that floats (and integer, but they just have max in min values) are not capable of holding very small numbers (after a dot; take a look at IEEE 754 standard) without loss of precision.

The size of a float is platform-dependent, although a maximum of approximately 1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format).

why is this happening

PHP uses precision ini-setting for determining wanted number of digits in a float.

trokymchuk
  • 127
  • 7