javascript - PHP ROUND 与 Javascript ROUND

标签 javascript php

我发现一个很奇怪的问题,问题是PHP和Javascript中的ROUND方法计算结果不一样!?

请看下面的例子:

PHP

echo round(175.5); // 176
echo round(-175.5); // -176

Javascript

console.log(Math.round(175.5)); // 176
console.log(Math.round(-175.5)); // -175 <-why not -176!!??

有人知道为什么吗?以及如何使 Javascript 和 PHP 得到相同的结果?

最佳答案

这不是问题,很好documented

If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞. Note that this differs from many languages' round() functions, which often round this case to the next integer away from zero, instead (giving a different result in the case of negative numbers with a fractional part of exactly 0.5).

如果你想在 Javascript 上有相同的行为,我会使用

var n = -175.5;
var round = Math.round(Math.abs(n))*(-1)

关于javascript - PHP ROUND 与 Javascript ROUND,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42791070/

相关文章:

javascript - 当我的 div 滑动时 float 元素不滑动,而是卡住,为什么?

javascript - polymer 铂金推送消息元件

php - PyroCMS 导航栏中的三级导航

php - 如何将 Unix 时间戳转换为 hhmmss?

php - 今天 PDO 是否转义 "%"和 "_"

php - 我过度查询 MySql 数据库。另一种检索大量数据的方法?

javascript - 我应该如何检查 Jasmine 或javascript中的排序语句

javascript - 悬停时导航栏下方的线条

javascript - 拖放指令 - IE 中未触发事件

PHP 目标 iframe 并给它一个 ?cat