在Java中将Double转换为Integer

Any way to cast java.lang.Double to java.lang.Integer ? 有什么方法可以将java.lang.Double为java.lang.Integer吗
摘要由CSDN通过智能技术生成

本文翻译自:Cast Double to Integer in Java

Any way to cast java.lang.Double to java.lang.Integer ? 有什么方法可以将java.lang.Doublejava.lang.Integer吗?

It throws an exception 它引发了一个例外

"java.lang.ClassCastException: java.lang.Double incompatible with java.lang.Integer" “java.lang.ClassCastException:java.lang.Double与java.lang.Integer不兼容”


#1楼

参考:https://stackoom.com/question/cBva/在Java中将Double转换为Integer


#2楼

double a = 13.34;
int b = (int) a;

System.out.println(b); //prints 13

#3楼

I see three possibilities. 我看到三种可能性。 The first two cut off the digits, the last one rounds to the nearest Integer. 前两个截断数字,最后一个截止到最接近的整数。

double d = 9.5;
int i = (int)d;
//i = 9

Double D = 9.5;
int i = Integer.valueOf(D.intValue());
//i = 9

double d = 9.5;
Long L = Math.round(d);
int i = Integer.valueOf(L.intValue());
//i = 10

#4楼

Double d = 100.00;
Integer i = d.intValue();

One should also add that it works with autoboxing. 还应该补充一点,它适用于自动装箱。

Otherwise, you get an int (primitive) and then can get an Integer from there: 否则,你得到一个int(原始),然后从那里得到一个Integer:

Integer i = new Integer(d.intValue());

#5楼

Indeed, the simplest way is to use intValue() . 实际上,最简单的方法是使用intValue() However, this merely returns t

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值