• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // © 2020 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 package com.ibm.icu.impl.number;
4 
5 import com.ibm.icu.impl.units.ComplexUnitsConverter;
6 import com.ibm.icu.impl.units.ConversionRates;
7 import com.ibm.icu.impl.units.MeasureUnitImpl;
8 import com.ibm.icu.util.MeasureUnit;
9 
10 /**
11  * A MicroPropsGenerator which converts a measurement from one MeasureUnit to
12  * another. In particular, the output MeasureUnit may be a mixed unit. (The
13  * input unit may not be a mixed unit.)
14  */
15 public class UnitConversionHandler implements MicroPropsGenerator {
16 
17     private final MicroPropsGenerator fParent;
18     private MeasureUnit fOutputUnit;
19     private ComplexUnitsConverter fComplexUnitConverter;
20 
21     /**
22      * @param targetUnit Specifies the output MeasureUnit. The input MeasureUnit
23      *     is derived from it: in case of a mixed unit, the biggest unit is
24      *     taken as the input unit. If not a mixed unit, the input unit will be
25      *     the same as the output unit and no unit conversion takes place.
26      * @param parent    The parent MicroPropsGenerator.
27      */
UnitConversionHandler(MeasureUnit targetUnit, MicroPropsGenerator parent)28     public UnitConversionHandler(MeasureUnit targetUnit, MicroPropsGenerator parent) {
29         this.fOutputUnit = targetUnit;
30         this.fParent = parent;
31         MeasureUnitImpl targetUnitImpl = MeasureUnitImpl.forIdentifier(targetUnit.getIdentifier());
32         this.fComplexUnitConverter = new ComplexUnitsConverter(targetUnitImpl, new ConversionRates());
33     }
34 
35     /**
36      * Obtains the appropriate output values from the Unit Converter.
37      */
38     @Override
processQuantity(DecimalQuantity quantity)39     public MicroProps processQuantity(DecimalQuantity quantity) {
40         MicroProps result = this.fParent.processQuantity(quantity);
41 
42         quantity.roundToInfinity(); // Enables toDouble
43         ComplexUnitsConverter.ComplexConverterResult complexConverterResult
44                 = this.fComplexUnitConverter.convert(quantity.toBigDecimal(), result.rounder);
45 
46         result.outputUnit = this.fOutputUnit;
47         UsagePrefsHandler.mixedMeasuresToMicros(complexConverterResult, quantity, result);
48 
49         return result;
50     }
51 }
52