舍入Java中的负数 [英] Rounding negative numbers in Java

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

问题描述

根据维基百科在舍入负数时,您可以舍入绝对数字。因此,通过这种推理,-3.5将四舍五入为-4。但是当我使用java.lang.Math.round(-3.5)返回-3时。有人可以解释一下吗?

According to Wikipedia when rounding a negative number, you round the absolute number. So by that reasoning, -3.5 would be rounded to -4. But when I use java.lang.Math.round(-3.5) returns -3. Can someone please explain this?

推荐答案

根据 javadoc


返回与
参数最接近的long。结果通过添加1/2来舍入为
整数,取结果的
下限,并将
结果转换为long类型。换句话说,
的结果等于
的表达式:

Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression:

(long)Math.floor (a + 0.5d)

从概念上讲,你将向上。换句话说,到下一个整数大于比值大,-3大于-3.5,而-4小于。

Conceptually, you round up. In other words, to the next integer greater than the value and -3 is greater than -3.5, while -4 is less.

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

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