I have an issue with some json code where decimal numbers MUST be encoded without quotes and maintain two decimal places
e.g.
{12.34, 33.40, 25.00}
My problem is that the array I have creates the numbers as string
foreach($numbers as $n)
{
$result[] = number_format($n, 2, '.', '');
}
json_encode($result);
// result = {"12.34", "33.40", "25.00"}
I had similar issie with this. This may not be the best code but it work for me. Maybe it can help you. Try this (I am using codeigniter):
function getData() {
$data = $this->Teplomer_model->showData(); //get your data from database as return $query->result();
//create array
$arr = array();
//foreach data to array
foreach ($data as $row) {
$arr[] = array(
"id" => $row->id_teplota,
"datum" => $row->cas_teplota,
"teplota" => $row->teplota_teplota,
"vlhkost" => $row->vlhkost_teplota
);
}
//echo array as json and check if there is any numbers
echo json_encode($arr, JSON_NUMERIC_CHECK );
}
And output:
{"id":3,"datum":"2019-02-08 14:03:31","teplota":22.33,"vlhkost":19.7},{"id":4,"datum":"2019-02-08 14:18:35","teplota":23,"vlhkost":19}
You could do:
$result[] = (float) number_format($n, 2, '.', '');
Result:
[12.42,33.4,25]
You can use floatval()
:
$result[] = floatval(number_format($n, 2, '.', ''));
Came across a similar problem. The only way to achieve this is to build the raw json object rather than using json_encode.
$jsonStr = '{';
$lastElement = count($numbers);
$i = 1;
foreach($numbers as $n)
{
$jsonStr .= number_format($n, 2, '.', '');
if($i != $lastElement){
$jsonStr .= ',';
}
$i++;
}
$jsonStr .= '}';
echo $jsonStr;
I know it's not the nicest way to code, but it's the only way to keep decimal points in a json object.