[英]Java - Format number to print decimal portion only **without decimal**
只需將輸出更改為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.