Math.round方法

本文深入探讨了Java Math类中round()方法的使用,包括两个版本:float型和double型。通过具体示例,详细解释了如何实现数值的四舍五入,并对不同输入值的输出进行了演示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Math.round()

java.lang.Math类有两个round()方法,定义如下:

public static int round(float);
public static long round(double);

它们都返回整数,且采用四舍五入进行运算,运算规则如下:
(1).如果参数为正数,小数点后采用四四舍五入,如果小数点后面>=0.5则整数部分加1,否则舍弃小数点后面的数据。
(2).如果参数是负数,如果小数点后面的<-0.5,则负数整数部分加上-1.否则舍弃小数点后面的数据。


测试代码:
public class Main {

public static void main(String[] args) {


System.out.println("Math.round(1.4):"+Math.round(1.4));
System.out.println("Math.round(1.5):"+Math.round(1.5));
System.out.println("Math.round(1.6):"+Math.round(1.6));
System.out.println("Math.round(-1.4):"+Math.round(-1.4));
System.out.println("Math.round(-1.5):"+Math.round(-1.5));
System.out.println("Math.round(-1.6):"+Math.round(-1.6));


}
}


输出:

Math.round(1.4):1
Math.round(1.5):2
Math.round(1.6):2
Math.round(-1.4):-1
Math.round(-1.5):-1
Math.round(-1.6):-2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值