下面的示例向您展示Math该类的一些方法,可用于舍入一个数字的值。这些方法是Math.ceil(),Math.floor()和Math.round()。
package org.nhooo.example.math;
public class GetRoundedValueExample {
public static void main(String[] args) {
Double number = 1.5D;
// 获得大于或等于
// 参数,等于一个数学整数
double roundUp = Math.ceil(number);
System.out.println("Result of rounding up of " + number + " = " + roundUp);
// 获得小于或等于最大值的最大值
// 参数,等于一个数学整数
double roundDown = Math.floor(number);
System.out.println("Result of rounding down of " + number + " = " + roundDown);
// 获取最接近参数的long值
long round1 = Math.round(number);
System.out.println("Rounding result of " + number + " (in long) = " + round1);
// 获取最接近参数的int值
int round2 = Math.round(number.floatValue());
System.out.println("Rounding result of " + number + " (in int) = " + round2);
}
}这是程序的结果:
Result of rounding up of 1.5 = 2.0 Result of rounding down of 1.5 = 1.0 Rounding result of 1.5 (in long) = 2 Rounding result of 1.5 (in int) = 2