Search in sources :

Example 6 with MeasureUnit

use of android.icu.util.MeasureUnit in project j2objc by google.

the class MeasureFormat method formatMeasure.

private StringBuilder formatMeasure(Measure measure, ImmutableNumberFormat nf, StringBuilder appendTo, FieldPosition fieldPosition) {
    Number n = measure.getNumber();
    MeasureUnit unit = measure.getUnit();
    if (unit instanceof Currency) {
        return appendTo.append(currencyFormat.format(new CurrencyAmount(n, (Currency) unit), new StringBuffer(), fieldPosition));
    }
    StringBuffer formattedNumber = new StringBuffer();
    StandardPlural pluralForm = QuantityFormatter.selectPlural(n, nf.nf, rules, formattedNumber, fieldPosition);
    String formatter = getPluralFormatter(unit, formatWidth, pluralForm.ordinal());
    return QuantityFormatter.format(formatter, formattedNumber, appendTo, fieldPosition);
}
Also used : MeasureUnit(android.icu.util.MeasureUnit) Currency(android.icu.util.Currency) StandardPlural(android.icu.impl.StandardPlural) CurrencyAmount(android.icu.util.CurrencyAmount)

Example 7 with MeasureUnit

use of android.icu.util.MeasureUnit in project j2objc by google.

the class MeasureFormat method formatMeasureRange.

/**
 * Format a range of measures, such as "3.4-5.1 meters". It is the caller’s
 * responsibility to have the appropriate values in appropriate order,
 * and using the appropriate Number values.
 * <br>Note: If the format doesn’t have enough decimals, or lowValue ≥ highValue,
 * the result will be a degenerate range, like “5-5 meters”.
 * <br>Currency Units are not yet supported.
 *
 * @param lowValue low value in range
 * @param highValue high value in range
 * @return the formatted string.
 * @deprecated This API is ICU internal only.
 * @hide original deprecated declaration
 * @hide draft / provisional / internal are hidden on Android
 */
@Deprecated
public final String formatMeasureRange(Measure lowValue, Measure highValue) {
    MeasureUnit unit = lowValue.getUnit();
    if (!unit.equals(highValue.getUnit())) {
        throw new IllegalArgumentException("Units must match: " + unit + " ≠ " + highValue.getUnit());
    }
    Number lowNumber = lowValue.getNumber();
    Number highNumber = highValue.getNumber();
    final boolean isCurrency = unit instanceof Currency;
    UFieldPosition lowFpos = new UFieldPosition();
    UFieldPosition highFpos = new UFieldPosition();
    StringBuffer lowFormatted = null;
    StringBuffer highFormatted = null;
    if (isCurrency) {
        Currency currency = (Currency) unit;
        int fracDigits = currency.getDefaultFractionDigits();
        int maxFrac = numberFormat.nf.getMaximumFractionDigits();
        int minFrac = numberFormat.nf.getMinimumFractionDigits();
        if (fracDigits != maxFrac || fracDigits != minFrac) {
            DecimalFormat currentNumberFormat = (DecimalFormat) numberFormat.get();
            currentNumberFormat.setMaximumFractionDigits(fracDigits);
            currentNumberFormat.setMinimumFractionDigits(fracDigits);
            lowFormatted = currentNumberFormat.format(lowNumber, new StringBuffer(), lowFpos);
            highFormatted = currentNumberFormat.format(highNumber, new StringBuffer(), highFpos);
        }
    }
    if (lowFormatted == null) {
        lowFormatted = numberFormat.format(lowNumber, new StringBuffer(), lowFpos);
        highFormatted = numberFormat.format(highNumber, new StringBuffer(), highFpos);
    }
    final double lowDouble = lowNumber.doubleValue();
    String keywordLow = rules.select(new PluralRules.FixedDecimal(lowDouble, lowFpos.getCountVisibleFractionDigits(), lowFpos.getFractionDigits()));
    final double highDouble = highNumber.doubleValue();
    String keywordHigh = rules.select(new PluralRules.FixedDecimal(highDouble, highFpos.getCountVisibleFractionDigits(), highFpos.getFractionDigits()));
    final PluralRanges pluralRanges = Factory.getDefaultFactory().getPluralRanges(getLocale());
    StandardPlural resolvedPlural = pluralRanges.get(StandardPlural.fromString(keywordLow), StandardPlural.fromString(keywordHigh));
    String rangeFormatter = getRangeFormat(getLocale(), formatWidth);
    String formattedNumber = SimpleFormatterImpl.formatCompiledPattern(rangeFormatter, lowFormatted, highFormatted);
    if (isCurrency) {
        // Nasty hack
        // have to call this for the side effect
        currencyFormat.format(1d);
        Currency currencyUnit = (Currency) unit;
        StringBuilder result = new StringBuilder();
        appendReplacingCurrency(currencyFormat.getPrefix(lowDouble >= 0), currencyUnit, resolvedPlural, result);
        result.append(formattedNumber);
        appendReplacingCurrency(currencyFormat.getSuffix(highDouble >= 0), currencyUnit, resolvedPlural, result);
        return result.toString();
    // StringBuffer buffer = new StringBuffer();
    // CurrencyAmount currencyLow = (CurrencyAmount) lowValue;
    // CurrencyAmount currencyHigh = (CurrencyAmount) highValue;
    // FieldPosition pos = new FieldPosition(NumberFormat.INTEGER_FIELD);
    // currencyFormat.format(currencyLow, buffer, pos);
    // int startOfInteger = pos.getBeginIndex();
    // StringBuffer buffer2 = new StringBuffer();
    // FieldPosition pos2 = new FieldPosition(0);
    // currencyFormat.format(currencyHigh, buffer2, pos2);
    } else {
        String formatter = getPluralFormatter(lowValue.getUnit(), formatWidth, resolvedPlural.ordinal());
        return SimpleFormatterImpl.formatCompiledPattern(formatter, formattedNumber);
    }
}
Also used : MeasureUnit(android.icu.util.MeasureUnit) Currency(android.icu.util.Currency) StandardPlural(android.icu.impl.StandardPlural)

Example 8 with MeasureUnit

use of android.icu.util.MeasureUnit in project j2objc by google.

the class MeasureFormat method formatMeasurePerUnit.

/**
 * Formats a single measure per unit.
 *
 * An example of such a formatted string is "3.5 meters per second."
 *
 * @param measure  the measure object. In above example, 3.5 meters.
 * @param perUnit  the per unit. In above example, it is MeasureUnit.SECOND
 * @param appendTo formatted string appended here.
 * @param pos      The field position.
 * @return appendTo.
 */
public StringBuilder formatMeasurePerUnit(Measure measure, MeasureUnit perUnit, StringBuilder appendTo, FieldPosition pos) {
    MeasureUnit resolvedUnit = MeasureUnit.resolveUnitPerUnit(measure.getUnit(), perUnit);
    if (resolvedUnit != null) {
        Measure newMeasure = new Measure(measure.getNumber(), resolvedUnit);
        return formatMeasure(newMeasure, numberFormat, appendTo, pos);
    }
    FieldPosition fpos = new FieldPosition(pos.getFieldAttribute(), pos.getField());
    int offset = withPerUnitAndAppend(formatMeasure(measure, numberFormat, new StringBuilder(), fpos), perUnit, appendTo);
    if (fpos.getBeginIndex() != 0 || fpos.getEndIndex() != 0) {
        pos.setBeginIndex(fpos.getBeginIndex() + offset);
        pos.setEndIndex(fpos.getEndIndex() + offset);
    }
    return appendTo;
}
Also used : MeasureUnit(android.icu.util.MeasureUnit) Measure(android.icu.util.Measure) DontCareFieldPosition(android.icu.impl.DontCareFieldPosition) FieldPosition(java.text.FieldPosition)

Example 9 with MeasureUnit

use of android.icu.util.MeasureUnit in project j2objc by google.

the class MeasureUnitTest method generateCXXHConstants.

// DO NOT DELETE THIS FUNCTION! It may appear as dead code, but we use this to generate code
// for MeasureFormat during the release process.
static void generateCXXHConstants(String thisVersion) {
    Map<String, MeasureUnit> seen = new HashMap<String, MeasureUnit>();
    System.out.println();
    TreeMap<String, List<MeasureUnit>> allUnits = getAllUnits();
    for (Map.Entry<String, List<MeasureUnit>> entry : allUnits.entrySet()) {
        String type = entry.getKey();
        if (type.equals("currency")) {
            continue;
        }
        for (MeasureUnit unit : entry.getValue()) {
            String code = unit.getSubtype();
            String name = toCamelCase(unit);
            String javaName = toJAVAName(unit);
            checkForDup(seen, name, unit);
            if (isDraft(javaName)) {
                System.out.println("#ifndef U_HIDE_DRAFT_API");
            }
            System.out.println("    /**");
            System.out.println("     * Returns unit of " + type + ": " + code + ".");
            System.out.println("     * Caller owns returned value and must free it.");
            System.out.println("     * @param status ICU error code.");
            if (isDraft(javaName)) {
                System.out.println("     * @draft ICU " + getVersion(javaName, thisVersion));
            } else {
                System.out.println("     * @stable ICU " + getVersion(javaName, thisVersion));
            }
            System.out.println("     */");
            System.out.printf("    static MeasureUnit *create%s(UErrorCode &status);\n\n", name);
            if (isDraft(javaName)) {
                System.out.println("#endif /* U_HIDE_DRAFT_API */");
            }
        }
    }
}
Also used : MeasureUnit(android.icu.util.MeasureUnit) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap)

Example 10 with MeasureUnit

use of android.icu.util.MeasureUnit in project j2objc by google.

the class MeasureUnitTest method testSimplePer.

@Test
public void testSimplePer() {
    Object DONT_CARE = null;
    Object[][] data = new Object[][] { // per unit pattern
    { FormatWidth.WIDE, 1.0, MeasureUnit.SECOND, "1 pound per second", DONT_CARE, 0, 0 }, { FormatWidth.WIDE, 2.0, MeasureUnit.SECOND, "2 pounds per second", DONT_CARE, 0, 0 }, // compound pattern
    { FormatWidth.WIDE, 1.0, MeasureUnit.MINUTE, "1 pound per minute", DONT_CARE, 0, 0 }, { FormatWidth.WIDE, 2.0, MeasureUnit.MINUTE, "2 pounds per minute", DONT_CARE, 0, 0 }, // per unit
    { FormatWidth.SHORT, 1.0, MeasureUnit.SECOND, "1 lb/s", DONT_CARE, 0, 0 }, { FormatWidth.SHORT, 2.0, MeasureUnit.SECOND, "2 lb/s", DONT_CARE, 0, 0 }, // compound
    { FormatWidth.SHORT, 1.0, MeasureUnit.MINUTE, "1 lb/min", DONT_CARE, 0, 0 }, { FormatWidth.SHORT, 2.0, MeasureUnit.MINUTE, "2 lb/min", DONT_CARE, 0, 0 }, // per unit
    { FormatWidth.NARROW, 1.0, MeasureUnit.SECOND, "1#/s", DONT_CARE, 0, 0 }, { FormatWidth.NARROW, 2.0, MeasureUnit.SECOND, "2#/s", DONT_CARE, 0, 0 }, // compound
    { FormatWidth.NARROW, 1.0, MeasureUnit.MINUTE, "1#/min", DONT_CARE, 0, 0 }, { FormatWidth.NARROW, 2.0, MeasureUnit.MINUTE, "2#/min", DONT_CARE, 0, 0 }, // field positions
    { FormatWidth.SHORT, 23.3, MeasureUnit.SECOND, "23.3 lb/s", NumberFormat.Field.DECIMAL_SEPARATOR, 2, 3 }, { FormatWidth.SHORT, 23.3, MeasureUnit.SECOND, "23.3 lb/s", NumberFormat.Field.INTEGER, 0, 2 }, { FormatWidth.SHORT, 23.3, MeasureUnit.MINUTE, "23.3 lb/min", NumberFormat.Field.DECIMAL_SEPARATOR, 2, 3 }, { FormatWidth.SHORT, 23.3, MeasureUnit.MINUTE, "23.3 lb/min", NumberFormat.Field.INTEGER, 0, 2 } };
    for (Object[] row : data) {
        FormatWidth formatWidth = (FormatWidth) row[0];
        Number amount = (Number) row[1];
        MeasureUnit perUnit = (MeasureUnit) row[2];
        String expected = row[3].toString();
        NumberFormat.Field field = (NumberFormat.Field) row[4];
        int startOffset = ((Integer) row[5]).intValue();
        int endOffset = ((Integer) row[6]).intValue();
        MeasureFormat mf = MeasureFormat.getInstance(ULocale.ENGLISH, formatWidth);
        FieldPosition pos = field != null ? new FieldPosition(field) : new FieldPosition(0);
        String prefix = "Prefix: ";
        assertEquals("", prefix + expected, mf.formatMeasurePerUnit(new Measure(amount, MeasureUnit.POUND), perUnit, new StringBuilder(prefix), pos).toString());
        if (field != DONT_CARE) {
            assertEquals("startOffset", startOffset, pos.getBeginIndex() - prefix.length());
            assertEquals("endOffset", endOffset, pos.getEndIndex() - prefix.length());
        }
    }
}
Also used : FormatWidth(android.icu.text.MeasureFormat.FormatWidth) FieldPosition(java.text.FieldPosition) Field(java.lang.reflect.Field) MeasureUnit(android.icu.util.MeasureUnit) Measure(android.icu.util.Measure) MeasureFormat(android.icu.text.MeasureFormat) NumberFormat(android.icu.text.NumberFormat) Test(org.junit.Test)

Aggregations

MeasureUnit (android.icu.util.MeasureUnit)16 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)7 List (java.util.List)7 Map (java.util.Map)7 TreeMap (java.util.TreeMap)7 Test (org.junit.Test)6 MeasureFormat (android.icu.text.MeasureFormat)4 FormatWidth (android.icu.text.MeasureFormat.FormatWidth)4 Measure (android.icu.util.Measure)4 Pair (android.icu.impl.Pair)3 ULocale (android.icu.util.ULocale)3 StandardPlural (android.icu.impl.StandardPlural)2 Currency (android.icu.util.Currency)2 Field (java.lang.reflect.Field)2 FieldPosition (java.text.FieldPosition)2 DontCareFieldPosition (android.icu.impl.DontCareFieldPosition)1 NumberFormat (android.icu.text.NumberFormat)1 CurrencyAmount (android.icu.util.CurrencyAmount)1 HashSet (java.util.HashSet)1