本文介紹了如何在不強制轉換的情況下將 double 轉換為 long?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
在不強制轉換的情況下將 double 轉換為 long 的最佳方法是什么?
What is the best way to convert a double to a long without casting?
例如:
double d = 394.000;
long l = (new Double(d)).longValue();
System.out.println("double=" + d + ", long=" + l);
推薦答案
假設您對截斷為零感到滿意,只需強制轉換:
Assuming you're happy with truncating towards zero, just cast:
double d = 1234.56;
long x = (long) d; // x = 1234
這將比通過包裝類更快 - 更重要的是,它更具可讀性.現在,如果您需要始終接近零"以外的舍入,則需要稍微復雜一些的代碼.
This will be faster than going via the wrapper classes - and more importantly, it's more readable. Now, if you need rounding other than "always towards zero" you'll need slightly more complicated code.
這篇關于如何在不強制轉換的情況下將 double 轉換為 long?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!