search

Home  >  Q&A  >  body text

php json_decode float loses decimal point

var_dump(json_decode('{"price":5.00}', true));

Result:
array(1) {
["price"]=>
float(5)//But the expectation is 5.00, the decimal point can be retained
}

为情所困为情所困2800 days ago1729

reply all(7)I'll reply

  • 为情所困

    为情所困2017-05-16 13:16:32

    It’s not a problem with json_decode, it’s the output function itself,

    var_dump(5.00);//输出float(5)
    echo 5.00;//输出5
    print 5.00;//输出5

    json_encode retains decimal points by setting optional options

    echo json_encode([5.00], JSON_PRESERVE_ZERO_FRACTION);//输出[5.0],但这也不是期望的[5.00]
    
    echo sprintf('%.2f', 5);//保留两位小数

    reply
    0
  • PHPz

    PHPz2017-05-16 13:16:32

    var_dump(json_decode('{"price":"5.00"}', true));

    reply
    0
  • 迷茫

    迷茫2017-05-16 13:16:32

    var_dump is a typed print.

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-16 13:16:32

    https://www.bytelang.com/o/s/...

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 13:16:32

    This is simple, just change 5.00 into string type

    reply
    0
  • 高洛峰

    高洛峰2017-05-16 13:16:32

    This has nothing to do with jeon_encode. It should be formatted during output.

    echo number_format($price, 2, '.', '');

    or

    echo sprintf('%.2f', $price);

    reply
    0
  • ringa_lee

    ringa_lee2017-05-16 13:16:32

    var_dump(json_decode('{"price":"5.00"}', true));

    reply
    0
  • Cancelreply