2013-10-03 82 views
0

我有一個雙值 - double d = 1.67303521E8; 無論我用什麼格式,我無法得到實際的解決方案。如何舍入/格式十進制後的數字,如果十進制值包含E作爲一項

我想:

DecimalFormat df = new DecimalFormat("#.000"); 

public static double round(double value, int places) { 
    if (places < 0) throw new IllegalArgumentException(); 

    long factor = (long) Math.pow(10, places); 
    value = value * factor; 
    long tmp = Math.round(value); 
    return (double) tmp/factor; 
} 

但始終輸出1.67303521E8。 S0最後我用

str.substring(0,5) 

我想知道什麼是真正的解決方案來解決這個問題

+0

什麼是您預期的輸出? –

回答

1

這樣,它應該格式化你想要的方式:

//This is just an object that can format numeric values into strings... 
DecimalFormat df = new DecimalFormat("#.000"); 

//computation 
long factor = (long) Math.pow(10, places); 
value = value * factor; 
long tmp = Math.round(value); 
double result = (double) tmp/factor; 

//formatting to string of specified format 
String formattedValue = df.format(result); 

//optional... 
System.out.println(formattedValue); 

你的錯可以 - 這是常見的 - 是你假設通過做某事,你可以奇蹟般地改變格式的雙值是在內存中存儲。這不是真的。雙打,日期等始終存儲在本地結構中,您必須格式它們可以以適當的指定格式呈現給人類。

但是,你有一個熾熱錯誤的串()的方法:E格式 - 也被稱爲是科學記數法 - 的E,指定哪個值10指數後,必須指定一個指數通過......這重要信息丟失在您的實現乘...

1.67303521E8 

實際上是

167303521 

而且不

1.673 
1

再試

System.out.println(new DecimalFormat("#.000").format(1.67303521E8)); 

輸出

167303521.000

+0

我沒有看到這與我的回答有何不同。 – ppeterka