2011-02-18 5 views
4

engineering notation에 문자열로 측정 단위를 자동으로 포맷하는 방법을 찾으려고합니다. 지수는 항상 3의 배수이지만 kilo, mega, milli, micro 접두사로 표시된다는 점에서 과학 표기법의 특별한 경우입니다.자동으로 Java의 엔지니어링 단위로 측정 형식을 지정하십시오.

이것은 SI 단위와 접두사의 전체 범위를 처리해야한다는 점을 제외하면 this post과 유사합니다.

예를 들어, 나는 양을 포맷하는 라이브러리 후 해요하도록 : 12345.6789 Hz로는 1234567.89 J 1 MJ 또는 1.23 MJ 또는 1.2345 MJ로 포맷 될 12 kHz에서 또는 12.346 kHz에서 또는 12.3456789 kHz에서로 포맷 될 것이다 등등.

JSR-275/JScience는 단위 측정을 잘 처리하지만 아직 측정 크기에 따라 자동으로 가장 적절한 스케일링 접두사를 찾아 낼 수있는 무언가를 찾고 있습니다.

건배, 샘.

+0

이것은 직접 구현을 롤링하는 간단한 방법입니다. 유일한 까다로운 부분은 SI 단위가 이미 미터법 접두어를 가지고있는 질량과 같은 양을 다루는 것입니다. –

+0

@Anon 질량은 적절한 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 여야합니다. 또한, 저는 여러분이 "340um"(0.34mm가 아닌)을 원하기 때문에 두 번째 루프는 while (tval <1)이어야한다고 확신합니다. –

+0

알겠습니다. 나는 그것들을 던질 것이다. 나는 소수점 3 자리 안에있는 것이 괜찮다고 가정했다. 우리는 구성 요소가 1 <= c <1000이되기를 원합니다. 명확한 설명을 해주셔서 감사합니다! – corsiKa

+0

댓글 권한이없는 사용자의 코멘트 (Xp-ert) : 'if (tval! = 0) {'before'while (tval > 1000.0) {'and'}''return tval + prefixes.get (order) + type; '이전에, 그렇지 않으면 앱은 값이'0 '일 때 두 번째 루프에서 영원히 반복합니다. – Anne

관련 문제