- 1. ceil() 向上取整
- 2. floor() 向下取整
- 3. round() 四舍五入
- 4.拓展
取整函数主要有三种:ceil()、floor()、round()
1. ceil() 向上取整函数名: ceil
用 法: double ceil(double x);
功 能: 返回大于或者等于指定表达式的最小整数。
头文件:math.h
返回数据类型:double
package com.test;
public class CeilTest {
private static final double[] TEST_DATA = {1, 1.3, 1.6, 0, -1, -1.3, -1.6 };
public static void main(String[] args) {
for(double num : TEST_DATA){
test(num);
}
}
public static void test(double num){
System.out.println(num+"的Math.ceil结果:"+Math.ceil(num));
}
}
向上取整的时候,正数,则直接将当前整数加一;
负数,则将整数后面的数据抹除;
整数,则不变。
说明
在C语言的库函数中,floor函数的语法如下:
#include
double floor( double arg );
功能: 函数返回不大于arg的最大整数值。
#include#include int main(void) { printf("floor(+2.7) = %+.1fn", floor(2.7)); printf("floor(-2.7) = %+.1fn", floor(-2.7)); printf("floor(-0.0) = %+.1fn", floor(-0.0)); printf("floor(-Inf) = %+fn", floor(-INFINITY)); }
//程序执行结果 floor(+2.7) = +2.0 floor(-2.7) = -3.0 floor(-0.0) = -0.0 floor(-Inf) = -inf
package com.test;
public class CeilTest {
private static final double[] TEST_DATA = {1, 1.3, 1.6, 0, -1, -1.3, -1.6 };
public static void main(String[] args) {
for(double num : TEST_DATA){
test(num);
}
}
public static void test(double num){
System.out.println(num+"的Math.floor结果:"+Math.floor(num));
}
}
3. round() 四舍五入
Round函数返回一个数值,该数值是按照指定的小数位数进行四舍五入运算的结果。
语法
round(number,digits)
参数
number,要四舍五入的数,digits是要小数点后保留的位数
如果 digits 大于 0,则四舍五入到指定的小数位。
如果 digits 等于 0,则四舍五入到最接近的整数。
如果 digits 小于 0,则在小数点左侧进行四舍五入。
如果round函数只有参数number,等同于digits 等于 0。
返回值
四舍五入后的值
=ROUND(3.19, 1) 将 3.19 四舍五入到一个小数位 (3.2)
=ROUND(2.649, 1) 将 2.649 四舍五入到一个小数位 (2.6)
=ROUND(-5.574, 2) 将 -5.574 四舍五入到两小数位 (-5.57)
=ROUND(18.8, -1) 将 18.8 四舍五入到小数点左侧一位 (20)。这个参数-1表示取整到十位数。
package com.test;
public class CeilTest {
private static final double[] TEST_DATA = {1, 1.3, 1.6, 0, -1, -1.3, -1.6 };
public static void main(String[] args) {
for(double num : TEST_DATA){
test(num);
}
}
public static void test(double num){
System.out.println(num+"的Math.round结果:"+Math.round(num));
}
}
4.拓展
Roundup函数
Rounddown函数



