有没有办法让JScience输出更加“人性化”?格式? [英] Is there a way to make JScience output in a more "human friendly" format?
问题描述
当我使用toString()获取JScience Amount对象时,我得到如下结果:
When I use toString() for JScience Amount objects I get results like this:
(7.5 ± 4.4E-16) mph
这不是很糟糕,但我真的很想输出类似的东西:
This isn't awful, but I'd really like it to output something like:
7.5 miles per hour
有没有一种简单的方法可以做到这一点?
Is there an easy way to do this?
编辑:为了澄清,我希望有一个解决方案这适用于任何类型单位(或至少所有预定义单位)的任何金额,而不仅仅是mph。
edit: Just to clarify, I'm hoping for a solution that will work for any Amount with any type of Units (or at least all of the pre-defined ones), not just "mph".
推荐答案
虽然它丢弃了错误和单位,但您可以这样做:
Although it discards the errors and units, you can do something like this:
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) mph
7.5 miles per hour
附录:我是希望有适用于任何单位的任何金额的解决方案。
您仍然需要提供自己的标签来替换默认的 UnitFormat
;标签字符受 isValidIdentifier()
的限制。您也可以替换自己的 AmountFormat $ c根据@RogerLindsjö的建议,$ c>
。此示例打印估计值的任意数量的有效数字和标签的有效变体。另请参见 TypeFormat
。
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
这篇关于有没有办法让JScience输出更加“人性化”?格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!