如何通过四舍五入在Java中将double转换为int? [英] How to cast a double to an int in Java by rounding it down?
本文介绍了如何通过四舍五入在Java中将double转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在 Java 中将 double 转换为 int,但数值必须始终向下取整.即 99.99999999 -> 99
I need to cast a double to an int in Java, but the numerical value must always round down. i.e. 99.99999999 -> 99
推荐答案
转换为 int 隐式丢弃任何小数.无需调用 Math.floor()(假设为正数)
Casting to an int implicitly drops any decimal. No need to call Math.floor() (assuming positive numbers)
简单地使用 (int) 进行类型转换,例如:
Simply typecast with (int), e.g.:
System.out.println((int)(99.9999)); // Prints 99
话虽如此,它确实与 Math.floor
有不同的行为,后者向负无穷大 (@Chris Wong) 舍入
This being said, it does have a different behavior from Math.floor
which rounds towards negative infinity (@Chris Wong)
这篇关于如何通过四舍五入在Java中将double转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文