我正在創建一個總是採用0.xxx格式的DOUBLE變量。雖然我希望每次出現三位小數數字,但我不想看到前導零(例如:.275)。我找到了許多方法來刪除STRING中的前導零,但不使用DOUBLE變量。平均數爲零
爲了給出更多的細節,我將一個int除以另一個int來獲得double。我可以使用printf/.3f來獲得千分之一的位置,但是%0.3f會導致錯誤。我必須錯過簡單的東西,但沒有找到我的錯誤。
我正在創建一個總是採用0.xxx格式的DOUBLE變量。雖然我希望每次出現三位小數數字,但我不想看到前導零(例如:.275)。我找到了許多方法來刪除STRING中的前導零,但不使用DOUBLE變量。平均數爲零
爲了給出更多的細節,我將一個int除以另一個int來獲得double。我可以使用printf/.3f來獲得千分之一的位置,但是%0.3f會導致錯誤。我必須錯過簡單的東西,但沒有找到我的錯誤。
它看起來像使用DecimalFormat
作品:
import java.text.DecimalFormat;
public class DecimalPrintNoZero
{
public static void main(String[] args)
{
double d = 0.275;
DecimalFormat df = new DecimalFormat("#.000");
System.out.println(df.format(d));
}
}
參考文獻:
http://developer.android.com/reference/java/text/DecimalFormat.html
發佈我的問題後,我在DecimalFormat上找到了一個視頻。我很高興看到這個答案,因爲它給了我一些背景。這就是說,它工作。我終於能夠得到適當的顯示變量,現在我可以繼續我的項目。感謝所有的迴應! – Kevin 2015-04-02 19:34:25
可以使用DecimalFormat類。喜歡的東西:
System.out.println(new DecimalFormat(".###").format(x));
十進制格式將工作
public class DoublePrinter {
public static void main(String[] args) {
Double d = 0.325;
DecimalFormat format = new DecimalFormat("0.000");
Double price2 = Double.parseDouble(format.format(d));
System.out.println(price2);
String s = format.format(d);
System.out.println("s is '" + s + "'");
}
}
一些代碼將是偉大的.. – Asim 2015-04-02 07:21:04
當你顯示它,它永遠是一個字符串,有時隱藏。爲什麼不明確並刪除前導零呢? – AntonH 2015-04-02 07:23:21