如何將double
值轉換爲int
執行以下操作:雙轉換爲int,捨去
Double If x = 4.97542. Convert to int x = 4.
Double If x = 4.23544. Convert to int x = 4.
也就是說,答案總是捨去。
如何將double
值轉換爲int
執行以下操作:雙轉換爲int,捨去
Double If x = 4.97542. Convert to int x = 4.
Double If x = 4.23544. Convert to int x = 4.
也就是說,答案總是捨去。
如果您明確地將轉換爲double
轉換爲int
,則小數部分將被截斷。例如:
int x = (int) 4.97542; //gives 4 only
int x = (int) 4.23544; //gives 4 only
此外,您還可以使用Math.floor()
法圓的情況下,值要在返回double
值。
double myDouble = 420.5;
//Type cast double to int
int i = (int)myDouble;
System.out.println(i);
雙值是420.5和應用打印出的420
整數值如果雙爲Double
資本d(裝箱原始值):
Double d = 4.97542;
int i = (int) d.doubleValue();
// or directly:
int i2 = d.intValue();
如果這個double已經是一個原始的double
,那麼你簡單地施放它:
double d = 4.97542;
int i = (int) d;
你能告訴我雙人和雙人有什麼區別嗎? – 2014-04-27 07:48:46
double是原始浮點值。 Double是一個Java對象。 – penguin 2015-11-03 21:23:53
我想我有更好的輸出,特別是對於雙數據類型排序。
儘管這個問題已經被標記回答,也許這將幫助別人;
Arrays.sort(newTag, new Comparator<String[]>() {
@Override
public int compare(final String[] entry1, final String[] entry2) {
final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
return time1.compareTo(time2);
}
});
使用Double
或double
另一種選擇或者是使用Double.valueOf(double d).intValue();
。簡單幹淨的
謝謝,解決我的問題 – Vogatsu 2012-04-23 12:40:33
是什麼意思爲「寬鬆十進制值」?它是否與調用'Math.floor()'相同的數字? – 2015-12-27 00:17:52