1

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".

sanity
  • 35,347
  • 40
  • 135
  • 226
  • Have you tried setting your own format on org.jscience.physics.amount.AmountFormat? – Roger Lindsjö Dec 15 '11 at 12:59
  • @Roger I have not, is there a way to do what I need in a general way with it? – sanity Dec 15 '11 at 13:04
  • It seems fairly easy to set a static amount format. The javadoc even has an example. See http://jscience.org/api/org/jscience/physics/amount/AmountFormat.htmlMaybe the getExactDigitsInstance is what you need. – Roger Lindsjö Dec 15 '11 at 13:48

1 Answers1

2

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
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Right, however I'm hoping for a solution that works for any amount with any units, mph was just an example – sanity Dec 15 '11 at 12:43