2017-09-26 15 views
-1
static double round(double input) { //rounds a double input to the 2 decimals. 
    return Math.round(input*100.0)/100.0; 
} 

上面的函數是我的代碼中的一個函數,它將double輸入舍入爲2位小數。我注意到每當返回值是小數點後第二位的數字(I.E.2.20,3.30,5.40等)時,我使用System.out.println()打印這個返回值。函數,打印2.2,3.3,5.4,在小數點第二位丟失零。但是,對於小數點後的數字(I.E。0.00,3.0等),每當打印時,小數點後1的零不會丟失。只有當double有小數點'.00'時,我怎樣才能將double轉換爲整數? (Java)

我的意圖是讓打印結果在其最後的十進制數中丟失零,因爲這是不必要的。我認爲這可以通過將double類型轉換爲int類型來完成,特別是當round函數的返回結果的小數位數爲.00時。我怎樣才能檢測到這種情況,併成功地將其改爲int類型?

+0

的[複製如何很好地格式化浮動號碼字符串沒有不必要的小數點0?](https://stackoverflow.com/q/703396/5221149) – Andreas

回答

0
static int round(double input) { //rounds a double input to the 2 decimals. 
if(Math.floor(input) == Math.ceil(input){ 
return (int) input; 
} 
return -1; 
} 

你可以指定返回類型爲雙並期待一個int來作爲回報,如果你想返回類型是整數,使函數返回類型整數

0

我想你可以使用java.text.NumberFormat類來設置分數位數的最小數目。

NumberFormat numberFormat = NumberFormat.getInstance(); numberFormat.setMinimumFractionDigits(2); System.out.println(numberFormat .format(yourNumber));

希望能有用〜

0

將雙數格式的數字乘以100,然後將數字除以10,然後再乘以10在新的數字中提取最後兩位數字,如果兩位數字均爲0,那麼只需鍵入原始數字(int)即可。這樣你就不會在數字的最後得到兩個零。希望我解決你的問題,不要問任何澄清的情況下...

0

檢查雙解析爲int是等於雙層,像

if (input == (int)input) 
    { 
     // print (int)input here 
    } 
相關問題