问题
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?
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".
回答1:
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");
Console:
(7.5 ± 4.4E-16) mph 7.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);
Console:
7.5 miles_per_hour
来源:https://stackoverflow.com/questions/8514293/is-there-a-way-to-make-jscience-output-in-a-more-human-friendly-format