【问题标题】:Java: Double to IntegerJava:双倍到整数
【发布时间】:2020-10-11 07:07:21
【问题描述】:

我知道我不能直接在 java 中将 Double 转换为 Integer,但我总是可以执行以下操作从 Double 获取 Integer,

public static void main(String args[]) {
  Double d = 2.3;
  Integer i = d.intValue(); // d.intValue() autoboxed to Integer
  
  System.out.println("Success");
  
}

为什么 Java 不给我这个内置的能力,这样我就不必每次自己都这样做了?

【问题讨论】:

  • 因为(I)它是一个缩小(精度损失)转换,即使你使用doubleint,你也不能没有强制转换,以及(ii)你 应该在这种代码中使用doubleint
  • Java 不会将对象隐式转换为其他对象。
  • @khelwood 你确定吗? Integer i = 1; Double d = i;呢?
  • @MarquisofLorne 这会给你一个incompatible types 错误。
  • @MarquisofLorne 整数 i = 1;双 d = i;也不好用

标签: java casting integer double


【解决方案1】:

您可以将此代码打包到方法中。

public static Integer doubleToInteger(Double d){
    return d.intValue();
}

【讨论】:

  • 请不要只发布代码作为答案,还要解释您的代码的作用以及它如何解决问题的问题。带有解释的答案通常更有帮助,质量更高,更有可能吸引投票。
猜你喜欢
  • 1970-01-01
  • 2013-03-30
  • 2012-10-31
  • 1970-01-01
  • 1970-01-01
  • 2011-04-10
  • 1970-01-01
  • 2013-05-07
  • 1970-01-01
相关资源
最近更新 更多