读书人

java.lang.Math种中round()和floor()区

发布时间: 2012-08-24 10:00:21 作者: rapoo

java.lang.Math类中round()和floor()区别
来源:http://hi.baidu.com/lvzhnan/blog/item/0943763513b52043241f144e.html
public static int round
(floata);

public static long round
(doublea);

public static double floor
(doublea);

round实际相当于(int)Math.floor(a + 0.5f);(int)Math.floor(a + 0.5d)。

对于正数:floor是不超过整数部分,round是(int)Math.floor(a + 0.5f),相当于四舍五入。

对于负数:floor是不超过整数部分,round是(int)Math.floor(a + 0.5f)。

Java代码

import java.lang.Math;
public class TestRound {
public static void main(String[] args) {
double d1 = 3.14;
double d2 = 3.5;
double d3 = -3.14;
double d4 = -3.5;
System.out.println(Math.round(d1)); // 3
System.out.println(Math.round(d2)); // 4
System.out.println(Math.round(d3)); // -3
System.out.println(Math.round(d4)); // -3

System.out.println(Math.floor(d1)); // 3.0
System.out.println(Math.floor(d2)); // 3.0
System.out.println(Math.floor(d3)); // -4.0
System.out.println(Math.floor(d4)); // -4.0
}
}

读书人网 >编程

热点推荐