簡體   English   中英

將Double對象轉換為int

[英]Casting Double object to int

如何從Double對象轉換為int? 以下代碼可以正常運行,但看起來有點不合常規(強制轉換兩次):

Double d = new Double(4.0);
int i = (int)(double)d;

當我嘗試int i = (int)d ,我從Eclipse中收到一個錯誤( Cannot cast from Double to int ),這是有道理的。 但是,有沒有更簡單的方法將Double對象轉換為int?

Double.intValue()

是提供的執行該轉換的方法。

如果將double轉換為int,則將丟失十進制值。因此,4.99 double變為4 int。 如果仍然想轉換而不是嘗試-

int i = d.intValue();

在您的情況下,您使用

Double.intValue()

作為將Double Object轉換為Integer的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM