簡體   English   中英

Java-僅顯示小數部分的格式編號**不帶小數**

[英]Java - Format number to print decimal portion only **without decimal**

之前有人問過這個問題( 格式化十進制數 ),但沒有回答如何不顯示十進制數就回答了這個問題。 我一直在尋找小時無濟於事的答案。 提前致謝!

例:

    System.out.println("It would take " + oneMileMins + " minutes and " + oneMileDfSecs.format(oneMileSecs) + " seconds for the person to run one mile.");

輸出:人跑一英里需要x分鍾和.yy秒。

我希望.yy只是yy

只需將輸出更改為oneMileDfSecs.format(oneMileSecs).replace(".", "")

編輯:羅德尼說:“ He did not ask for the proper equation he only asked how to remove the decimal. ”,所以我刪除了以下內容,以尊重他。

補充說明

就像 @Alan 所說的那樣, oneMileSecs應該等於(int)((oneMile % 1)*60) ,在這種情況下,擺脫小數點的方式有點不同

1)。 如果您聲明:

double oneMileSecs = (int)((oneMile % 1)*60)

然后將輸出更改為:

String.valueOf(oneMileSecs).substring(0,String.valueOf(oneMileSecs).indexOf("."))

2)。 如果您聲明:

int oneMileSecs = (int)((oneMile % 1)*60)

然后直接輸出oneMileSecs ,因為它是一個int ,不會產生十進制符號

不確定這是否是您要查找的答案,因為它沒有回答標題中的問題(Fev的答案就是這樣),但是我認為這應該為特定示例提供正確的結果:

private static void calcOneMile(double mph)
{
    double oneMile =  60 / mph;
    int oneMileMins = (int)oneMile;
    double oneMileFraction = oneMile % 1;
    int oneMileSecs = (int)(oneMileFraction * 60);
    System.out.println("It would take " + oneMileMins + " minutes and " + oneMileSecs + " seconds for the person to run one mile.");
}

或簡化為:

private static void calcOneMile(double mph)
{
    int secondsToRunMile = (int)(1.0 / (mph / 3600));
    System.out.println("It would take " + (secondsToRunMile / 60) + " minutes and " + (secondsToRunMile % 60) + " seconds for the person to run one mile.");
}

暫無
暫無

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

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