如何在Java中使用Math函数实现数字舍入和取整
发布时间:2023-07-03 05:19:27
在Java中,可以使用Math类提供的一些函数来实现数字的舍入和取整操作。
1. Math.ceil():向上取整
Math.ceil() 函数返回大于或等于给定数字的最小整数。
例如,Math.ceil(4.6) 返回结果为 5。
2. Math.floor():向下取整
Math.floor() 函数返回小于或等于给定数字的最大整数。
例如,Math.floor(4.6) 返回结果为 4。
3. Math.round():四舍五入
Math.round() 函数返回最接近给定数字的整数,如果距离两个整数相等,则返回偶数。
例如,Math.round(4.6) 返回结果为 5,Math.round(4.4) 返回结果为 4。
4. Math.trunc():去除小数部分
Math.trunc() 函数返回整数部分,去除了小数部分。
例如,Math.trunc(4.6) 返回结果为 4,Math.trunc(-4.6) 返回结果为 -4。
以下是示例代码:
public class MathTest {
public static void main(String[] args) {
double number = 4.6;
double ceilResult = Math.ceil(number);
System.out.println("向上取整结果:" + ceilResult);
double floorResult = Math.floor(number);
System.out.println("向下取整结果:" + floorResult);
long roundResult = Math.round(number);
System.out.println("四舍五入结果:" + roundResult);
long truncResult = (long) Math.trunc(number);
System.out.println("去除小数部分结果:" + truncResult);
}
}
运行上述代码将输出:
向上取整结果:5.0 向下取整结果:4.0 四舍五入结果:5 去除小数部分结果:4
这样就可以使用Math函数在Java中实现数字的舍入和取整操作了。
