Math.round()函数

Math.round()可以简单的理解为四舍五入函数,在负数的情况下0.5不进位。

public class TestDemo {

	public static void main(String[] args) {
		long r1=Math.round(11.1);
		long r2=Math.round(11.5);
		long r3=Math.round(11.6);
		long r4=Math.round(-11.1);
		long r5=Math.round(-11.5);
		long r6=Math.round(-11.6);
		
		System.out.println("11.1->"+r1);
		System.out.println("11.5->"+r2);
		System.out.println("11.6->"+r3);
		System.out.println("-11.1->"+r4);
		System.out.println("-11.5->"+r5);
		System.out.println("-11.6->"+r6);
		

	}

}
运行结果




下面是这个函数的定义


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 typelong. In other words, the result is equal to the value of the expression:

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

Special cases:

  • If the argument is NaN, the result is 0.
  • If the argument is negative infinity or any value less than or equal to the value of Long.MIN_VALUE, the result is equal to the value of Long.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Long.MAX_VALUE, the result is equal to the value of Long.MAX_VALUE.
Parameters:
a a floating-point value to be rounded to a long.
Returns:

the value of the argument rounded to the nearest long value.


返回最接近的一个long,计算方式是加上0.5再向下取整(Math.floor()向下取整函数),这就是为什么-11.5返回结果为-11。

如果内容不是个数字,返回0;

如果内容负无限大或者小于等于long的最小值,返回Long.MIN_VALUE;

如果内容正无限大或者大于等于long的最大值返回Long.MAX_VALUE;

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值