2016-06-07 40 views
2

我想使用DecimalFormat,它以工程表示法(指數是3的倍數)格式化數字,並使用固定數量的小數位數。小數位數應該可以由模式配置。使用固定小數位數的工程符號格式的雙精度格式

這是可能與java.text.DecimalFormat類。 有其他選擇嗎?

這裏是輸出12.345E3代替12.34E3測試用例:

public static void main(String[] args) 
{ 
    Locale.setDefault(Locale.ENGLISH); 
    DecimalFormat df = new DecimalFormat("##0.00E0"); 

    String realOutput = df.format(12345); 
    String expected = "12.34E3"; 

    System.out.println(realOutput); 
    if (Objects.equals(realOutput, expected)) 
    { 
     System.out.println("OK"); 
    } 
    else 
    { 
     System.err.println("Formatted output " + realOutput + " differs from documented output " + expected); 
    } 
} 
+3

[谷歌是你的朋友(http://www.labbookpages.co.uk/software/java/engNotation.html) – specializt

+0

谷歌僅僅是你的第二個最佳朋友。你最好的朋友是具有幾乎所有「內置」類/概念的傑出javadoc。 – GhostCat

+0

Javadoc沒有幫我找到解決方案。嘗試使用工程符號和兩個小數數字來尋找一個模式,這兩個數字適用於兩個數字:12345和1234.工程符號不起作用或小數位數不能修復。 – Uli

回答

0

private final static int PREFIX_OFFSET = 5; 
private final static String[] PREFIX_ARRAY = {"f", "p", "n", "µ", "m", "", "k", "M", "G", "T"}; 

public static String convert(double val, int dp) 
{ 
    // If the value is zero, then simply return 0 with the correct number of dp 
    if (val == 0) return String.format("%." + dp + "f", 0.0); 

    // If the value is negative, make it positive so the log10 works 
    double posVal = (val<0) ? -val : val; 
    double log10 = Math.log10(posVal); 

    // Determine how many orders of 3 magnitudes the value is 
    int count = (int) Math.floor(log10/3); 

    // Calculate the index of the prefix symbol 
    int index = count + PREFIX_OFFSET; 

    // Scale the value into the range 1<=val<1000 
    val /= Math.pow(10, count * 3); 

    if (index >= 0 && index < PREFIX_ARRAY.length) 
    { 
     // If a prefix exists use it to create the correct string 
     return String.format("%." + dp + "f%s", val, PREFIX_ARRAY[index]); 
    } 
    else 
    { 
     // If no prefix exists just make a string of the form 000e000 
     return String.format("%." + dp + "fe%d", val, count * 3); 
    } 
} 
0

你應該使用下列內容:

DecimalFormat format = new DecimalFormat("##0.0E0"); 

這裏http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

你可以找到答案對你部分「科學記法」中的問題

科學記數法中的數字表示爲尾數和冪的冪的乘積,例如,1234可以表示爲 1.234×10^3。尾數通常在1.0 < = x < 10.0範圍內,但不一定是。可以指示DecimalFormat僅通過模式來格式化和解析科學記數法;目前沒有工廠 方法創建科學記數法格式。在一種模式中, 指數字符後面緊跟着一個或多個數字 字符表示科學記數法。例如:「0。### E0」的格式爲 ,編號1234爲「1.234E3」。

指數字符後的數字字符數給出 最小指數位數。沒有最大限度。負指數 使用局部減號進行格式化,而不是來自模式的前綴和 後綴。這允許諸如「0。### E0 m/s」之類的模式。 整數位數的最小值和最大值被一起解釋爲 :如果整數位數的最大值大於 的最小值並且大於1,則強制指數爲最大整數位數的整數倍,並且最小的 的整數位數被解釋爲1.最常見的用途是 這是生成工程符號,其中指數是 的三倍,例如「## 0。##### E0" 。使用此模式, 號碼12345格式爲「12.345E3」,123456格式爲「123.456E3」。 否則,通過調整指數 來實現最小的整數位數。例如:用「00。### E0」 格式化的0.00123得出「12.3E-4」。尾數中的有效位數是 最小整數和最大分數位的總和,且不受最大整數位數的影響。例如,帶有「## 0。## E0」的12345格式的 是「12.3E3」。要顯示所有數字,請將重要的 數字計數設置爲零。有效數字的數量不會影響 解析。指數模式可能不包含分組分隔符。從this website採取

+0

我想用2個小數位來表示工程符號。 – Uli

+0

請嘗試使用不同數字的圖案:12345和1.2和12.3 – Uli

+0

您的意思是:「## 0#E0」? – Ivan