gpt4 book ai didi

java - 自动将测量格式化为 Java 中的工程单位

转载 作者:搜寻专家 更新时间:2023-10-31 20:15:45 27 4
gpt4 key购买 nike

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

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

例如,我正在寻找一个将格式化数量的库,以便:12345.6789 Hz 将被格式化为 12 kHz 或 12.346 kHz 或 12.3456789 kHz1234567.89 J 将被格式化为 1 MJ 或 1.23 MJ 或 1.2345 MJ等等。

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

干杯,山姆。

最佳答案

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);

}

}

关于java - 自动将测量格式化为 Java 中的工程单位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5036470/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com