douyan9417 2017-05-05 10:38
浏览 49
已采纳

PHP round($ num,2)和javascript toFixed(2)没有为此值53.955提供正确的输出

I have one php function and having

phpans = round(53.955,2)

and javascript function

var num  = 53.955;
var jsans = num.toFixed(2);
console.log(jsans);

both jsans and phpans is giving different $phpans = 53.96 ans jsans = 53.95 . I can not understand why this is happening .. Thanks is Advance

</div>
  • 写回答

2条回答 默认 最新

  • dousha7645 2017-05-05 10:44
    关注

    Because computers can't represent floating numbers properly. It's probably 53.95400000000009 or something like that. The way to deal with this is multiply by 100, round, then divide by 100 so the computer is only dealing with whole numbers.

    var start = 53.955,
            res1,
            res2;
        
        res1 = start.toFixed(2);
        res2 = (start * 100).toFixed(0) / 100;
        console.log(res1, res2);

    //Outputs
    "53.95"
    53.96
    
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目