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 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)