简体   繁体   English

PHP:防止 json_encode 将 float 转换为 int

[英]PHP: Prevent json_encode from converting float to int

I need to pass the amount in the form of decimals as in 50.00 to an API but when the amount is json_encoded it converts the amount to int 50.我需要将 50.00 中的小数形式的金额传递给 API 但是当金额为 json_encoded 时,它将金额转换为 int 50。

Sample code:示例代码:

echo json_encode(['amount' => 50.00]);

This displays这显示

{"amount":50} {“金额”:50}

I need the amount to stay as 50.00 itself.我需要将金额保持为 50.00 本身。 How do I do this?我该怎么做呢?

You may try to use JSON_PRESERVE_ZERO_FRACTION flag to make sure, that float values are always encoded as a float value.您可以尝试使用JSON_PRESERVE_ZERO_FRACTION标志来确保浮点值始终被编码为浮点值。 Note, that this option is available starting from PHP 5.6.6.请注意,此选项从 PHP 5.6.6 开始可用。

<?php
echo json_encode(['amount' => 50.00], JSON_PRESERVE_ZERO_FRACTION);
?>

Note, that although JSON_PRESERVE_ZERO_FRACTION is an option, the result (as @NigelRen mentioned in the comment) is 50.0 , not 50.00 .请注意,虽然JSON_PRESERVE_ZERO_FRACTION是一个选项,但结果(如评论中提到的@NigelRen)是50.0 ,而不是50.00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM