簡體   English   中英

將double轉換為Int,四舍五入

[英]Convert double to Int, rounded down

如何執行以下操作將double值轉換為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

此外,如果您想返回double Math.floor()值,也可以使用Math.floor()方法對值進行舍入。

如果double是具有大寫DDouble (裝箱的原始值):

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;
double myDouble = 420.5;
//Type cast double to int
int i = (int)myDouble;
System.out.println(i);

雙精度值是420.5,應用程序將打印出整數值420

使用Doubledouble另一個選項是使用Double.valueOf(double d).intValue(); 簡單干凈

我認為我有更好的輸出,尤其是對於雙重數據類型排序。

盡管此問題已被標記為已回答,但也許這會對其他人有所幫助。

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);
         }
    });

暫無
暫無

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

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