Is there a way to make JScience output in a more “human friendly” format?

前端 未结 1 1983
余生分开走
余生分开走 2021-01-25 08:17

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 ou

相关标签:
1条回答
  • 2021-01-25 09:06

    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
    
    0 讨论(0)
提交回复
热议问题