在Javascript中舍入负数 [英] Rounding of negative numbers in Javascript

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

问题描述

我们在JavaScript中遇到了 Math.round()的问题。问题是此函数不能正确舍入负数。例如:

We have come across a problem with Math.round() in JavaScript. The problem is that this function doesn't round correctly for negative numbers. For example :

1.5~ = 2

0.5~ = 1

-0.5~ = 0 //错误

-0.5 ~= 0 // Wrong

-1.5~ = -1 //错误

-1.5 ~= -1 // Wrong

根据算术舍入,这是不正确的。 -0.5的正确数字应为-1,-1.5应为-2。

And this is not correct according to arithmetic rounding. The correct numbers for -0.5 should be -1 and -1.5 should be -2.

是否有任何标准方法,在Javascript中正确舍入负数?

推荐答案

您可以在ES5中保存该标志并稍后申请;

You could save the sign and apply later, in ES5;

function round(v) {
    return (v >= 0 || -1) * Math.round(Math.abs(v));
}

console.log(round(1.5));  //  2
console.log(round(0.5));  //  1
console.log(round(-1.5)); // -2
console.log(round(-0.5)); // -1

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

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