V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
183387594
V2EX  ›  PHP

输出 float 数据的问题

  •  
  •   183387594 · 2019-01-24 10:02:27 +08:00 · 2755 次点击
    这是一个创建于 1891 天前的主题,其中的信息可能已经有所发展或是发生改变。

    想在输出的 json 里 输出 float 数据,可发现 浮在均衡中的一台机器 不论怎么操作都丢失精度 eg

    		echo  json_encode([
    			'x'=>1.71,
    			'xx'=>3.45,
    			'xxx'=>2.59,
    			'xxxx'=>2.47,
    			'xxxxx'=>0.01,
    		]);
    

    有问题的机器

    {"x":1.71,"xx":3.4500000000000002,"xxx":2.5899999999999999,"xxxx":2.4700000000000002,"xxxxx":0.01}
    

    其他机器输出

    {
    "x": 1.71,
    "xx": 3.45,
    "xxx": 2.59,
    "xxxx": 2.47,
    "xxxxx": 0.01
    }
    

    也尝试了

    function priceFormat($num)
    {
    	return (float)sprintf("%.2f",$num);
    }
    
    function priceFormat($num)
    {
    	return floatVal(sprintf("%.2f",$num));
    }
    

    都不行

    有人知道是什么原因吗

    4 条回复    2019-01-24 10:23:52 +08:00
    jfcherng
        1
    jfcherng  
       2019-01-24 10:20:33 +08:00   ❤️ 1
    jfcherng
        2
    jfcherng  
       2019-01-24 10:22:29 +08:00
    可能的解決方法, php.ini 設定 serialize_precision = -1
    183387594
        3
    183387594  
    OP
       2019-01-24 10:23:26 +08:00
    @jfcherng 谢谢,解决了 是这个问题 serialize_precision
    两个 php 的安装方式不一样 .ini 的 默认参数不同
    jfcherng
        4
    jfcherng  
       2019-01-24 10:23:52 +08:00
    ini_set('serialize_precision', -1); 在我這裡工作正常
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5395 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 07:06 · PVG 15:06 · LAX 00:06 · JFK 03:06
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.