gpt4 book ai didi

java - 有没有办法让 JScience 输出为 "human friendly"格式?

转载 作者:行者123 更新时间:2023-11-30 04:56:02 30 4
gpt4 key购买 nike

当我对 JScience Amount 对象使用 toString() 时,我得到如下结果:

(7.5 ± 4.4E-16) mph

这并不糟糕,但我真的希望它输出如下内容:

7.5 miles per hour

有没有简单的方法可以做到这一点?

编辑:只是为了澄清,我希望有一个解决方案适用于任何金额和任何类型的单位(或至少所有预定义的单位),而不仅仅是“英里/小时”。

最佳答案

尽管它会丢弃错误和单位,但您可以执行以下操作:

Amount<Velocity> x = Amount.valueOf(7.5, NonSI.MILES_PER_HOUR);
System.out.println(x);
System.out.println(
x.doubleValue(NonSI.MILES_PER_HOUR) + " miles per hour");

控制台:

(7.5 ± 4.4E-16) mph7.5 miles per hour

Addendum: I'm hoping for a solution that works for any amount with any units.

You'll still have to provide your own label to replace the default UnitFormat; the label characters are limited by isValidIdentifier(). You can also substitute your own AmountFormat, as suggested by @Roger Lindsjö. This example prints an arbitrary number of significant digits of the estimated value and a valid variation of your label. See also TypeFormat.

final UnitFormat uf = UnitFormat.getInstance();
uf.label(NonSI.MILES_PER_HOUR, "miles_per_hour");
AmountFormat.setInstance(new AmountFormat() {

@Override
public Appendable format(Amount<?> m, Appendable a) throws IOException {
TypeFormat.format(m.getEstimatedValue(), -1, false, false, a);
a.append(" ");
return uf.format(m.getUnit(), a);
}

@Override
public Amount<?> parse(CharSequence csq, Cursor c) throws IllegalArgumentException {
throw new UnsupportedOperationException("Parsing not supported.");
}
});
Amount<Velocity> x = Amount.valueOf(7.5, NonSI.MILES_PER_HOUR);
System.out.println(x);

控制台:

7.5 miles_per_hour

关于java - 有没有办法让 JScience 输出为 "human friendly"格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8514293/

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