【java Math.round()的各种用法示例,还有正负数据的不同对比】

概要

Math.round() 方法在 Java 中用于对浮点数进行四舍五入到最接近的整数。下面我将给出一些 Math.round() 的用法示例,包括正数和负数的对比。

示例

(1)正数四舍五入

double positiveNumber1 = 7.6;  
int roundedPositive1 = (int) Math.round(positiveNumber1);  
System.out.println(roundedPositive1); // 输出 8  
  
double positiveNumber2 = 7.4;  
int roundedPositive2 = (int) Math.round(positiveNumber2);  
System.out.println(roundedPositive2); // 输出 7  
  
double positiveNumber3 = 7.5;  
int roundedPositive3 = (int) Math.round(positiveNumber3);  
System.out.println(roundedPositive3); // 输出 8,因为 7.5 四舍五入到最近的整数是 8

(2)负数四舍五入

double negativeNumber1 = -7.6;  
int roundedNegative1 = (int) Math.round(negativeNumber1);  
System.out.println(roundedNegative1); // 输出 -8  
  
double negativeNumber2 = -7.4;  
int roundedNegative2 = (int) Math.round(negativeNumber2);  
System.out.println(roundedNegative2); // 输出 -7  
  
double negativeNumber3 = -7.5;  
int roundedNegative3 = (int) Math.round(negativeNumber3);  
System.out.println(roundedNegative3); // 输出 -7,因为 -7.5 四舍五入到最近的整数是 -7

(3)四舍五入到小数点后一位(自定义方法)

由于 Math.round() 不能直接四舍五入到小数点后一位,我们需要先乘以 10,再四舍五入,最后除以 10。

double numberWithDecimal1 = 7.64;  
double roundedToOneDecimal1 = Math.round(numberWithDecimal1 * 10.0) / 10.0;  
System.out.println(roundedToOneDecimal1); // 输出 7.6  
  
double numberWithDecimal2 = -7.64;  
double roundedToOneDecimal2 = Math.round(numberWithDecimal2 * 10.0) / 10.0;  
System.out.println(roundedToOneDecimal2); // 输出 -7.6

(4)四舍五入到小数点后两位(自定义方法)

同样地,为了四舍五入到小数点后两位,我们需要先乘以 100,再四舍五入,最后除以 100。

double numberWithDecimal1 = 7.646;  
double roundedToTwoDecimals1 = Math.round(numberWithDecimal1 * 100.0) / 100.0;  
System.out.println(roundedToTwoDecimals1); // 输出 7.65  
  
double numberWithDecimal2 = -7.644;  
double roundedToTwoDecimals2 = Math.round(numberWithDecimal2 * 100.0) / 100.0;  
System.out.println(roundedToTwoDecimals2); // 输出 -7.64

总结

在这些示例中,你可以看到 Math.round() 方法对正数和负数的处理是一致的:如果小数部分小于 0.5,则舍去;如果小数部分大于或等于 0.5,则进位。无论数字是正数还是负数,这个规则都适用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值