PHP有json_encode的十进制数字

时间:2014-06-21 22:52:57

标签: php json

我遇到了一些json代码的问题,其中十进制数必须不带引号编码并保持两位小数

e.g。

{12.34, 33.40, 25.00}

我的问题是我已经将数字创建为字符串

foreach($numbers as $n)
{
  $result[] = number_format($n, 2, '.', '');
}
json_encode($result);

// result = {"12.34", "33.40", "25.00"}

4 个答案:

答案 0 :(得分:4)

您可以使用floatval()

$result[] = floatval(number_format($n, 2, '.', ''));

答案 1 :(得分:3)

你可以这样做:

$result[] = (float) number_format($n, 2, '.', '');

结果:

[12.42,33.4,25]

答案 2 :(得分:1)

我对此也有类似的困扰。这可能不是最好的代码,但对我有用。也许可以帮到您。 试试这个(我正在使用codeigniter):

{
  "compilerOptions": {
    ...
    "lib": ["es2018", "dom"], // add `dom` to the array
    ...
  }
}

并输出:

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 );
}

答案 3 :(得分:0)

遇到类似问题。实现此目的的唯一方法是构建原始json对象,而不是使用json_encode。

while

我知道这不是最好的编码方式,但这是将小数点保留在json对象中的唯一方法。