2011-02-18 26 views
4

我試圖找到一種方法將測量和單位自動格式化爲engineering notation中的字符串。這是科學記數法的一個特例,其中指數總是三的倍數,但用千,兆,毫,微前綴表示。自動將度量格式化爲Java中的工程單位

這與this post類似,除了它應該處理整個SI單位和前綴的範圍。

例如,我將格式化數量的文庫之後是這樣的: 12345.6789赫茲將被格式化爲12 kHz或12.346 kHz或12.3456789千赫 1234567.89Ĵ將被格式化爲1 MJ或1.23 MJ或1.2345 MJ 依此類推。

JSR-275/JScience處理單位測量沒問題,但是我還沒有找到能夠根據測量的大小自動計算出最合適的縮放前綴的內容。

乾杯, 山姆。

+0

這似乎是一個簡單的地方推出自己的實施。唯一棘手的部分是處理像質量這樣的數量,其中SI單位已經有一個公制前綴。 –

+0

@如果你只是讓它用克來思考,即使它不是合適的SI單位,那麼非質量可能會很容易。 – corsiKa

回答

2
import java.util.*; 
class Measurement { 
    public static final Map<Integer,String> prefixes; 
    static { 
     Map<Integer,String> tempPrefixes = new HashMap<Integer,String>(); 
     tempPrefixes.put(0,""); 
     tempPrefixes.put(3,"k"); 
     tempPrefixes.put(6,"M"); 
     tempPrefixes.put(9,"G"); 
     tempPrefixes.put(12,"T"); 
     tempPrefixes.put(-3,"m"); 
     tempPrefixes.put(-6,"u"); 
     prefixes = Collections.unmodifiableMap(tempPrefixes); 
    } 

    String type; 
    double value; 

    public Measurement(double value, String type) { 
     this.value = value; 
     this.type = type; 
    } 

    public String toString() { 
     double tval = value; 
     int order = 0; 
     while(tval > 1000.0) { 
      tval /= 1000.0; 
      order += 3; 
     } 
     while(tval < 1.0) { 
      tval *= 1000.0; 
      order -= 3; 
     } 
     return tval + prefixes.get(order) + type; 
    } 

    public static void main(String[] args) { 
     Measurement dist = new Measurement(1337,"m"); // should be 1.337Km 
     Measurement freq = new Measurement(12345678,"hz"); // should be 12.3Mhz 
     Measurement tiny = new Measurement(0.00034,"m"); // should be 0.34mm 

     System.out.println(dist); 
     System.out.println(freq); 
     System.out.println(tiny); 

    } 

} 
+0

注意「kilo」應該是小寫的k。另外,我很確定你想要的是「340微米」(而不是0.34毫米),所以你的第二個循環應該是'while(tval <1)'。 –

+0

我明白了。我會把它們扔進去。我假設小數點後3位的數字沒有問題。看來我們希望任何組件都是1 <= c <1000.感謝您的澄清!我也把你扔進地圖中(儘管它不是確切的字母,它應該可以工作。) – corsiKa

+0

用戶無評論權限的評論(Xp-ert):添加'if(tval!= 0){''while'(tval > 1000.0){'和'}'在返回tval + prefixes.get(order)+ type;'之前,否則應用程序在值爲'0'時在第二個循環中永遠循環。 – Anne

相關問題