我发现一个很奇怪的问题,问题是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/