PHP number_format返回值为字符串而非数字的问题解决
PHP使用number_format后返回字符串,JSON输出不符合数字类型需求
问题说明
使用number_format处理数值后,返回结果为字符串类型,导致JSON输出里的balance字段是字符串格式,不符合预期的数字类型要求。
原代码
$calc = "500020.66000000"; $calc = number_format((float)$calc, 2, '.', ''); $return_data = [ 'data' => [ 'balance' => number_format((float)$calc, 2, '.', ''), ], ];
当前返回结果
{ "data": { "balance": "500020.66", "currency": "TRY" } }
期望返回结果
{ "data": { "balance": 500020.66, "currency": "TRY" } }
解决方法
- 修改PHP配置:在
php.ini中添加以下配置serialize_precision=-1 - 使用
round函数替代number_format:round($calc, 2);
内容的提问来源于stack exchange,提问作者ege memetoğlu
相关产品推荐
相关产品推荐

