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
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Math.round函数Math类中的一个方法,用于对一个数字进行四舍五入取整操作。根据引用\[1\]和引用\[2\]的解释,Math.round函数的工作原理是将原来的数字加上0.5后再向下取整。当小数点后第一位为5时,正数会向上取整,负数会向下取整。当小数点后第一位小于5时,正数和负数都会向下取整。当小数点后第一位大于5时,正数会向上取整,负数会向下取整。根据引用\[3\]中的代码示例,可以更清晰地理解Math.round函数的工作方式。例如,Math.round(0.4)的结果是0,Math.round(0.5)的结果是1,Math.round(-0.4)的结果是0,Math.round(-0.5)的结果是0。 #### 引用[.reference_title] - *1* *2* [Math.round()方法](https://blog.csdn.net/zhoushumin157016/article/details/51984436)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [Math.round()和Math.random()的使用方法和思路](https://blog.csdn.net/weixin_47269259/article/details/121698620)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值