如何从double转换为int圆顶

时间:2013-12-17 11:36:35

标签: java casting

我有代码:

double dd=2.99;
int ii=(int)(dd);//ii==2

我想在ii中有3个。有没有快速简单的方法?

5 个答案:

答案 0 :(得分:6)

您想要Math.round()或 - 如果您想要整理 - Math.ceil()。同样,有Math.floor()总是向下舍入。

非常挑剔,您应该注意Math.round( double )会返回long,因此如果您想将结果存储在int中,可能会失去精确度(对于非常大的doubles)。

答案 1 :(得分:2)

使用Math.ceil(dd)。它会将任何数字四舍五入到最接近的整数。同样地,Math.floor(dd)会将其向下舍入,而Math.round(dd)会向下/向上舍入,具体取决于哪个更接近。

对于记录,Math类包含大量有用的数学方法。

答案 2 :(得分:1)

对于Ceil,即a = 3:

double dd=2.99;
int a =Math.ceil(dd) 

对于场地:即a = 2

double dd=2.99;
int a =Math.Floor(dd)

答案 3 :(得分:0)

 double d=2.99;
 int i=(int) Math.ceil(d);
 System.out.println(i);

答案 4 :(得分:0)

使用java.lang.Math类的round方法。

Math.round(double);

以下是API文档的链接

http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#round(double)