You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 18:45:41