Java 数值计算

[color=red][b]java.lang.Math's floor(),ceil() and round()的区别:[/b][/color]
Just 贴 JDK:
[quote]public static double floor(double a)
Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.
floor返回的是不大于(小于or等于)参数的最大整数的floating-point value表示。

public static double ceil(double a)
Returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.
ceil返回的是不小于(大于or等于)参数的最小整数的floating-point value表示。

public static long round(double a)
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:
[b](long)Math.floor(a + 0.5d)[/b]
在做四舍五入运算时,我们可以使用round;但当参数为 [b]-xxx.5[/b] 时,四舍五入后得到的结果不是我们期待的,解决办法是先对参数取绝对值,然后再用round方法
[/quote]
Sources:
[url]http://blog.csdn.net/foart/archive/2009/06/24/4295645.aspx[/url]


[color=red][b]使用BigDecimal做精确的数值计算[/b]:[/color]
Java精确计算 - [url]http://blog.csdn.net/xiaosu_521/article/details/2065854[/url]


关于round方法结合面试题再多说说:
Math.round(11.5) = 12
Math.round(-11.5) = -11
Math.round(-11.3) = -11
Math.round(-11.8) = -12
析:[quote]
Math.round(11.5)
= (long)Math.floor(11.5 + 0.5)
= (long)Math.floor(12.0)
= (long)12.0
= 12

Math.round(-11.5)
= (long)Math.floor(-11.5 + 0.5)
= (long)Math.floor(-11.0)
= (long)-11.0
= -11

Math.round(-11.3)
= (long)Math.floor(-11.3 + 0.5)
= (long)Math.floor(-10.8)
= (long)-11.0
= -11

Math.round(-11.8)
= (long)Math.floor(-11.8 + 0.5)
= (long)Math.floor(-11.3)
= (long)-12.0
= -12
[/quote]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值