PHP ROUND对比Javascript ROUND [英] PHP ROUND vs Javascript ROUND

查看:44
本文介绍了PHP ROUND对比Javascript ROUND的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I found a very strange issue, the issue is the ROUND method in PHP and Javascript the calculation results are not the same!?

请参见以下示例:

PHP

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

JavaScript

Javascript

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

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

anyone know why? and how to make Javascript and PHP the same results?

推荐答案

这不是问题,很好

如果小数部分正好是0.5,则将参数舍入为在+∞方向上的下一个整数.请注意,这与许多语言的round()函数,通常会将这种情况四舍五入到下一个远离零的整数,而不是(在小数部分正好为0.5的负数的情况.

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上具有相同的行为,我会使用

If you want the same behaviour on Javascript, I would use

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

这篇关于PHP ROUND对比Javascript ROUND的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆