Android / Java:将数字四舍五入得到无小数
如何将十进制数舍入为整数。
3.50 => 4
4.5 => 5
3.4 => 3
你是如何用Java做到的? 谢谢!
如果你只使用正数,你也可以使用int i =(int)(d + 0.5)。
编辑:如果你想向上舍入负数(向正无穷大,例如-5.4变为-5),你也可以使用它。 如果你想要舍入到更高的幅度(舍入-5.4到-6),你最好使用另一个答案提出的其他function。
具有标准的舍入function? Math.round()
还有Math.floor()
和Math.ceil()
,具体取决于您的需要。
您可以使用
int i = Math.round(f); long l = Math.round(d);
其中f
和d
分别是float
和double
类型。
Java在Math类中提供了一些函数来执行此操作。 对于您的情况,请尝试Math.ceil(4.5)
,它将返回5。
new BigDecimal(3.4); Integer result = BigDecimal.ROUND_HALF_UP;
要么
Int i = (int)(202.22d);
使用Math.max你可以这样做:
(int) Math.max(1, (long) Math.ceil((double) (34) / 25)
这会给你2