[英]Convert double to int without rounding java
我想知道如何在 Java 中不四舍五入的情况下将 double 转换为 int,例如 3,9 double 到 39 int,提前致谢!
我想您可以将double
转换为String
,删除.
然后尝试将其解析为int
。
通过做这样的事情:
public static void main(String[] args) {
double input = 2.12345;
String stringInput = String.valueOf(input);
String withoutDot = stringInput.replace(".", "");
try {
int number = Integer.parseInt(withoutDot);
}
catch (NumberFormatException e) {
// Handle this exception gracefully
}
}
请注意,使用此解决方案时,当您的double
值具有许多小数点时,您将始终遇到NumberFormatException
。
如果您的double
值始终具有相同数量的小数点(例如 2),另一种解决方案是使用乘法:
public static void main(String[] args) {
double input = 2.12;
Double rounded = 2.12 * 100;
int number = rounded.intValue();
}
一般来说是不可能的。 因为 double 可以有比 int 多得多的数字。
double d = 3.111111111111111111111111111111;
System.out.println(Integer.MAX_VALUE);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.