Java中的取整与四舍五入方法实例

在Java中,处理浮点数时经常需要进行取整或四舍五入操作,本文将详细介绍Java中常用的取整和四舍五入的方法,并通过代码示例进行说明。
1. 基本概念
取整:将小数部分去掉,只保留整数部分,3.7取整后为3,而3.7取整后为4。
四舍五入:根据小数部分的值决定是向上还是向下取整,3.5四舍五入后为4,而3.5四舍五入后为4。
2. 取整方法
1 Math.floor()
Math.floor(double a) 返回小于或等于参数的最大整数,结果为double 类型。

public class FloorExample {
public static void main(String[] args) {
double num = 3.7;
double floorResult = Math.floor(num);
System.out.println("Math.floor(" + num + ") = " + floorResult); // 输出: Math.floor(3.7) = 3.0
}
}
2 Math.ceil()
Math.ceil(double a) 返回大于或等于参数的最小整数,结果为double 类型。
public class CeilExample {
public static void main(String[] args) {
double num = 3.2;
double ceilResult = Math.ceil(num);
System.out.println("Math.ceil(" + num + ") = " + ceilResult); // 输出: Math.ceil(3.2) = 4.0
}
}
3 Math.round()
Math.round(float a) 和Math.round(double a) 对参数进行四舍五入,结果为long 类型。
public class RoundExample {
public static void main(String[] args) {
double num = 3.5;
long roundResult = Math.round(num);
System.out.println("Math.round(" + num + ") = " + roundResult); // 输出: Math.round(3.5) = 4
}
}
3. 四舍五入方法
1 BigDecimal类
BigDecimal 提供了更精确的数值运算,包括四舍五入。
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalRoundExample {
public static void main(String[] args) {
BigDecimal num = new BigDecimal("3.55");
BigDecimal roundedNum = num.setScale(0, RoundingMode.HALF_UP);
System.out.println("BigDecimal Round: " + roundedNum); // 输出: BigDecimal Round: 4
}
}
表格归纳
| 方法 | 描述 | 结果类型 | 示例代码结果 |
| Math.floor() | 返回小于或等于参数的最大整数 | double | Math.floor(3.7) = 3.0 |
| Math.ceil() | 返回大于或等于参数的最小整数 | double | Math.ceil(3.2) = 4.0 |
| Math.round() | 对参数进行四舍五入 | long | Math.round(3.5) = 4 |
| BigDecimal | 提供精确的数值运算,包括四舍五入 | BigDecimal | new BigDecimal(“3.55”).setScale(0, RoundingMode.HALF_UP) = 4 |
相关问题与解答

问题1:为什么Math.round(3.5) 返回的是4 而不是3?
解答:Math.round() 方法在处理正数时,如果小数部分正好是.5,它会向远离零的方向舍入(即向上舍入)。Math.round(3.5) 会返回4。
问题2:使用BigDecimal 进行四舍五入时,如何指定舍入模式?
解答:在使用BigDecimal 进行四舍五入时,可以通过setScale 方法指定舍入模式。new BigDecimal("3.55").setScale(0, RoundingMode.HALF_UP) 表示将3.55 四舍五入到整数位,并使用HALF_UP 模式(即四舍五入),其他常见的舍入模式还包括RoundingMode.DOWN(向下舍入)和RoundingMode.UP(向上舍入)。
各位小伙伴们,我刚刚为大家分享了有关“java中的取整与四舍五入方法实例”的知识,希望对你们有所帮助。如果您还有其他相关问题需要解决,欢迎随时提出哦!














