How to fetch the conversion factor for any unit conversion

1.7k views Asked by At

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;
    }
}
1

There are 1 answers

1
razlebe On BEST ANSWER

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:

  • MultiplyConverter has a getFactor() method which returns the factor being used in the conversion.
  • AddConverter has a getOffset() method which returns the offset the converter adds in the conversion.
  • RationalConverter, if I understand it correctly, converts by multiplying the value being converted by the quotient of two numbers - the dividend and the divisor. The class has methods, getDividend() and getDivisor() for returning the dividend and the divisor, so you could perform the division yourself to approximate the quotient.

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;