javajsciencejsr-275

How to fetch the conversion factor for any unit conversion


When you convert between 2 entities, you usually do it via the UnitConverter. How should I find out what the conversion factor is? For example:

public static final Unit<Length> KILOMETRE = METER.times(1000);
public static final Unit<Length> CENTIMETRE = METRE.divide(100);

I would like to get the conversion factor programmatically from the converter interfaces (i.e. 1000 b/w KILOMETRE and METER or 1/100 in case of CENTIMETER to METRE)

I am not sure how to fetch this information from the UnitConverter interface.

EDIT1

protected double getConvFactor(Unit<Length> from, Unit<Length> to) {
    double factor = -1;

    UnitConverter unitConverter = from.getConverterTo(to);

    if (unitConverter instanceof MultiplyConverter) {
        MultiplyConverter multiplyConverter = (MultiplyConverter) unitConverter;
        factor = multiplyConverter.getFactor();
    } else if (unitConverter instanceof AddConverter) {
        AddConverter addConverter = (AddConverter) unitConverter;
        factor = addConverter.getOffset();
    } else if (unitConverter instanceof RationalConverter) {
        RationalConverter rationalConverter = (RationalConverter) unitConverter;
        double divisor = rationalConverter.getDivisor().doubleValue();
        double dividend = rationalConverter.getDividend().doubleValue();
        factor = divisor;
    }
}

Solution

  • Edit after further code posted by OP:

    UnitConverter is an abstract class, so one must derive from it to create a converter for the specific units you have in mind.

    If you're already using a class derived from UnitConverter, you'll have to check it's interface to see if the designer of that class was good enough to expose a method that returns the multiplication factor.

    Looking at some of the jscience classes derived from UnitConverter:

    So I think your code (below) is in error. The factor is NOT the divisor, as you have here - it's the quotient.

    RationalConverter rationalConverter = (RationalConverter) unitConverter;
    double divisor = rationalConverter.getDivisor().doubleValue();
    double dividend = rationalConverter.getDividend().doubleValue();
    factor = divisor;