Java如何四舍五入数字?
下面的示例向您展示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
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志