0

On My PHP server Float values changes when i print on website in json format. but working ok on localhost.

Code:

$float   = 1.440030394;
$value  = round($float,5); // 1.44003

$response = array();
$response['status']  = true;
$response['message'] = "success";
$response['values']  = $value;


echo json_encode($response);

// test if value is really true?
echo "<br>test<br>";
echo $value."-abc"; // Work ok if float convert to string

Localhost Response is ok, but on Live server response is

{
    "status": true,
    "message": "success",
    "values": 1.44035442150000012452200154
}
Test
1.44003-abc

Any solutions? i try functions : round, number_format but not working.

asad app
  • 321
  • 1
  • 2
  • 14

1 Answers1

0

Float uses mantissa and exponent representation to hold a number. That means that not all bits of the value are saved separately, and this results in an impossibility to represent all numbers.

You can see this for more details: How are floating point numbers stored in memory?.

Basically your number cannot be stored in a float, so any operations you do on it will result in a slight error.

You have 2 options here.

First one is that if the error is not too big for you and you can ignore it, you just need to truncate the number on output result.

Second one is to treat the number like a string or save each individual digit inside an array. This is actually what happens when you converted your number to string on your last edit. Your number is not a number any more, but a string and each of its digits are saved individually.

Almost all languages are based on float for numbers with decimals because of their versatility, but floats should not be used for data where each bit is important (like for money). You can open your console in browser (f12 by default and type 0.8 - 0.7) the output will be 0.100000000009 or something like that, because 0.1 doesn't have an exact representation, but the error is small enough to be ignored usually.

zozo
  • 8,230
  • 19
  • 79
  • 134