gpt4 book ai didi

javascript - PHP ROUND 与 Javascript ROUND

转载 作者:可可西里 更新时间:2023-11-01 00:02:02 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com