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 给外婆敬酒祝福语简短