您的位置:首页 > 游戏 > 游戏 > 【java Math.round()的各种用法示例,还有正负数据的不同对比】

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

2025/4/19 13:51:40 来源:https://blog.csdn.net/uutale/article/details/139473598  浏览:    关键词:【java Math.round()的各种用法示例,还有正负数据的不同对比】

文章目录

    • 概要
    • 示例
      • (1)正数四舍五入
      • (2)负数四舍五入
      • (3)四舍五入到小数点后一位(自定义方法)
      • (4)四舍五入到小数点后两位(自定义方法)
    • 总结

概要

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,则进位。无论数字是正数还是负数,这个规则都适用。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com