首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Java中自动将度量格式化为工程单位

在Java中自动将度量格式化为工程单位
EN

Stack Overflow用户
提问于 2011-02-18 08:35:40
回答 1查看 2.1K关注 0票数 5

我正在尝试找到一种在engineering notation中自动将度量和单位格式化为字符串的方法。这是科学记数法的一个特例,因为指数始终是3的倍数,但使用千、兆、毫微前缀表示。

这将类似于this post,除了它应该处理整个范围的SI单位和前缀。

例如,我正在寻找一个库,它将格式化数量,例如: 12345.6789 Hz将格式化为12 kHz或12.346 kHz或12.3456789 kHz 1234567.89 J将格式为1 MJ或1.23MJ或1.2345 MJ,依此类推。

JSR-275 / JScience可以处理单位度量,但是我还没有找到能够根据度量的大小自动计算出最合适的缩放前缀的方法。

干杯萨姆。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-02-18 08:45:37

代码语言:javascript
复制
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);

    }

}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5036470

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档