文章目录
- 概要
- 示例
- (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,则进位。无论数字是正数还是负数,这个规则都适用。