Search in sources :

Example 16 with MeasureFormat

use of android.icu.text.MeasureFormat in project j2objc by google.

the class TimeUnitTest method TestEqHashCode.

@Test
public void TestEqHashCode() {
    TimeUnitFormat tf = new TimeUnitFormat(ULocale.ENGLISH, TimeUnitFormat.FULL_NAME);
    MeasureFormat tfeq = new TimeUnitFormat(ULocale.ENGLISH, TimeUnitFormat.FULL_NAME);
    MeasureFormat tfne = new TimeUnitFormat(ULocale.ENGLISH, TimeUnitFormat.ABBREVIATED_NAME);
    MeasureFormat tfne2 = new TimeUnitFormat(ULocale.GERMAN, TimeUnitFormat.FULL_NAME);
    verifyEqualsHashCode(tf, tfeq, tfne);
    verifyEqualsHashCode(tf, tfeq, tfne2);
}
Also used : TimeUnitFormat(android.icu.text.TimeUnitFormat) MeasureFormat(android.icu.text.MeasureFormat) Test(org.junit.Test)

Example 17 with MeasureFormat

use of android.icu.text.MeasureFormat in project android_packages_apps_Settings by LineageOS.

the class Utils method formatElapsedTime.

/**
 * Returns elapsed time for the given millis, in the following format:
 * 2d 5h 40m 29s
 * @param context the application context
 * @param millis the elapsed time in milli seconds
 * @param withSeconds include seconds?
 * @return the formatted elapsed time
 */
public static CharSequence formatElapsedTime(Context context, double millis, boolean withSeconds) {
    SpannableStringBuilder sb = new SpannableStringBuilder();
    int seconds = (int) Math.floor(millis / 1000);
    if (!withSeconds) {
        // Round up.
        seconds += 30;
    }
    int days = 0, hours = 0, minutes = 0;
    if (seconds >= SECONDS_PER_DAY) {
        days = seconds / SECONDS_PER_DAY;
        seconds -= days * SECONDS_PER_DAY;
    }
    if (seconds >= SECONDS_PER_HOUR) {
        hours = seconds / SECONDS_PER_HOUR;
        seconds -= hours * SECONDS_PER_HOUR;
    }
    if (seconds >= SECONDS_PER_MINUTE) {
        minutes = seconds / SECONDS_PER_MINUTE;
        seconds -= minutes * SECONDS_PER_MINUTE;
    }
    final ArrayList<Measure> measureList = new ArrayList(4);
    if (days > 0) {
        measureList.add(new Measure(days, MeasureUnit.DAY));
    }
    if (hours > 0) {
        measureList.add(new Measure(hours, MeasureUnit.HOUR));
    }
    if (minutes > 0) {
        measureList.add(new Measure(minutes, MeasureUnit.MINUTE));
    }
    if (withSeconds && seconds > 0) {
        measureList.add(new Measure(seconds, MeasureUnit.SECOND));
    }
    if (measureList.size() == 0) {
        // Everything addable was zero, so nothing was added. We add a zero.
        measureList.add(new Measure(0, withSeconds ? MeasureUnit.SECOND : MeasureUnit.MINUTE));
    }
    final Measure[] measureArray = measureList.toArray(new Measure[measureList.size()]);
    final Locale locale = context.getResources().getConfiguration().locale;
    final MeasureFormat measureFormat = MeasureFormat.getInstance(locale, MeasureFormat.FormatWidth.NARROW);
    sb.append(measureFormat.formatMeasures(measureArray));
    if (measureArray.length == 1 && MeasureUnit.MINUTE.equals(measureArray[0].getUnit())) {
        // Add ttsSpan if it only have minute value, because it will be read as "meters"
        final TtsSpan ttsSpan = new TtsSpan.MeasureBuilder().setNumber(minutes).setUnit("minute").build();
        sb.setSpan(ttsSpan, 0, sb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    return sb;
}
Also used : Locale(java.util.Locale) TtsSpan(android.text.style.TtsSpan) Measure(android.icu.util.Measure) ArrayList(java.util.ArrayList) SpannableStringBuilder(android.text.SpannableStringBuilder) MeasureFormat(android.icu.text.MeasureFormat)

Example 18 with MeasureFormat

use of android.icu.text.MeasureFormat in project j2objc by google.

the class NumberFormatTest method TestCases.

// InputStream is will be closed by the ResourceReader.
@SuppressWarnings("resource")
@Test
public void TestCases() {
    String caseFileName = "NumberFormatTestCases.txt";
    java.io.InputStream is = NumberFormatTest.class.getResourceAsStream(caseFileName);
    ResourceReader reader = new ResourceReader(is, caseFileName, "utf-8");
    TokenIterator tokens = new TokenIterator(reader);
    Locale loc = new Locale("en", "US", "");
    DecimalFormat ref = null, fmt = null;
    MeasureFormat mfmt = null;
    String pat = null, str = null, mloc = null;
    boolean strict = false;
    try {
        for (; ; ) {
            String tok = tokens.next();
            if (tok == null) {
                break;
            }
            String where = "(" + tokens.getLineNumber() + ") ";
            int cmd = keywordIndex(tok);
            switch(cmd) {
                case 0:
                    // ref= <reference pattern>
                    ref = new DecimalFormat(tokens.next(), new DecimalFormatSymbols(Locale.US));
                    ref.setParseStrict(strict);
                    logln("Setting reference pattern to:\t" + ref);
                    break;
                case 1:
                    // loc= <locale>
                    loc = LocaleUtility.getLocaleFromName(tokens.next());
                    pat = ((DecimalFormat) NumberFormat.getInstance(loc)).toPattern();
                    logln("Setting locale to:\t" + loc + ", \tand pattern to:\t" + pat);
                    break;
                // f:
                case 2:
                // fp:
                case 3:
                // rt:
                case 4:
                case // p:
                5:
                    tok = tokens.next();
                    if (!tok.equals("-")) {
                        pat = tok;
                    }
                    try {
                        fmt = new DecimalFormat(pat, new DecimalFormatSymbols(loc));
                        fmt.setParseStrict(strict);
                    } catch (IllegalArgumentException iae) {
                        errln(where + "Pattern \"" + pat + '"');
                        iae.printStackTrace();
                        // consume remaining tokens
                        tokens.next();
                        // tokens.next();
                        if (cmd == 3)
                            tokens.next();
                        continue;
                    }
                    str = null;
                    try {
                        if (cmd == 2 || cmd == 3 || cmd == 4) {
                            // f: <pattern or '-'> <number> <exp. string>
                            // fp: <pattern or '-'> <number> <exp. string> <exp. number>
                            // rt: <pattern or '-'> <number> <string>
                            String num = tokens.next();
                            str = tokens.next();
                            Number n = ref.parse(num);
                            assertEquals(where + '"' + pat + "\".format(" + num + ")", str, fmt.format(n));
                            if (cmd == 3) {
                                // fp:
                                n = ref.parse(tokens.next());
                            }
                            if (cmd != 2) {
                                // != f:
                                assertEquals(where + '"' + pat + "\".parse(\"" + str + "\")", n, fmt.parse(str));
                            }
                        } else // p: <pattern or '-'> <string to parse> <exp. number>
                        {
                            str = tokens.next();
                            String expstr = tokens.next();
                            Number parsed = fmt.parse(str);
                            Number exp = ref.parse(expstr);
                            assertEquals(where + '"' + pat + "\".parse(\"" + str + "\")", exp, parsed);
                        }
                    } catch (ParseException e) {
                        errln(where + '"' + pat + "\".parse(\"" + str + "\") threw an exception");
                        e.printStackTrace();
                    }
                    break;
                case 6:
                    // perr: <pattern or '-'> <invalid string>
                    errln("Under construction");
                    return;
                case 7:
                    // pat: <pattern> <exp. toPattern, or '-' or 'err'>
                    String testpat = tokens.next();
                    String exppat = tokens.next();
                    boolean err = exppat.equals("err");
                    if (testpat.equals("-")) {
                        if (err) {
                            errln("Invalid command \"pat: - err\" at " + tokens.describePosition());
                            continue;
                        }
                        testpat = pat;
                    }
                    if (exppat.equals("-"))
                        exppat = testpat;
                    try {
                        DecimalFormat f = null;
                        if (testpat == pat) {
                            // [sic]
                            f = fmt;
                        } else {
                            f = new DecimalFormat(testpat);
                            f.setParseStrict(strict);
                        }
                        if (err) {
                            errln(where + "Invalid pattern \"" + testpat + "\" was accepted");
                        } else {
                            assertEquals(where + '"' + testpat + "\".toPattern()", exppat, f.toPattern());
                        }
                    } catch (IllegalArgumentException iae2) {
                        if (err) {
                            logln("Ok: " + where + "Invalid pattern \"" + testpat + "\" threw an exception");
                        } else {
                            errln(where + "Valid pattern \"" + testpat + "\" threw an exception");
                            iae2.printStackTrace();
                        }
                    }
                    break;
                case // fpc:
                8:
                    tok = tokens.next();
                    if (!tok.equals("-")) {
                        mloc = tok;
                        ULocale l = new ULocale(mloc);
                        try {
                            mfmt = MeasureFormat.getCurrencyFormat(l);
                        } catch (IllegalArgumentException iae) {
                            errln(where + "Loc \"" + tok + '"');
                            iae.printStackTrace();
                            // consume remaining tokens
                            tokens.next();
                            tokens.next();
                            tokens.next();
                            continue;
                        }
                    }
                    str = null;
                    try {
                        // fpc: <loc or '-'> <curr.amt> <exp. string> <exp. curr.amt>
                        String currAmt = tokens.next();
                        str = tokens.next();
                        CurrencyAmount target = parseCurrencyAmount(currAmt, ref, '/');
                        String formatResult = mfmt.format(target);
                        assertEquals(where + "getCurrencyFormat(" + mloc + ").format(" + currAmt + ")", str, formatResult);
                        target = parseCurrencyAmount(tokens.next(), ref, '/');
                        CurrencyAmount parseResult = (CurrencyAmount) mfmt.parseObject(str);
                        assertEquals(where + "getCurrencyFormat(" + mloc + ").parse(\"" + str + "\")", target, parseResult);
                    } catch (ParseException e) {
                        errln(where + '"' + pat + "\".parse(\"" + str + "\") threw an exception");
                        e.printStackTrace();
                    }
                    break;
                case // strict= true or false
                9:
                    strict = "true".equalsIgnoreCase(tokens.next());
                    logln("Setting strict to:\t" + strict);
                    break;
                case -1:
                    errln("Unknown command \"" + tok + "\" at " + tokens.describePosition());
                    return;
            }
        }
    } catch (java.io.IOException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            reader.close();
        } catch (IOException ignored) {
        }
    }
}
Also used : ResourceReader(android.icu.impl.data.ResourceReader) Locale(java.util.Locale) ULocale(android.icu.util.ULocale) ULocale(android.icu.util.ULocale) DecimalFormatSymbols(android.icu.text.DecimalFormatSymbols) CompactDecimalFormat(android.icu.text.CompactDecimalFormat) DecimalFormat(android.icu.text.DecimalFormat) IOException(java.io.IOException) IOException(java.io.IOException) CurrencyAmount(android.icu.util.CurrencyAmount) TokenIterator(android.icu.impl.data.TokenIterator) ParseException(java.text.ParseException) MeasureFormat(android.icu.text.MeasureFormat) Test(org.junit.Test)

Example 19 with MeasureFormat

use of android.icu.text.MeasureFormat in project j2objc by google.

the class PluralRangesTest method TestFormatting.

@Test
public void TestFormatting() {
    Object[][] tests = { { 0.0, 1.0, ULocale.FRANCE, FormatWidth.WIDE, MeasureUnit.FAHRENHEIT, "0–1 degré Fahrenheit" }, { 1.0, 2.0, ULocale.FRANCE, FormatWidth.WIDE, MeasureUnit.FAHRENHEIT, "1–2 degrés Fahrenheit" }, { 3.1, 4.25, ULocale.FRANCE, FormatWidth.SHORT, MeasureUnit.FAHRENHEIT, "3,1–4,25 °F" }, { 3.1, 4.25, ULocale.ENGLISH, FormatWidth.SHORT, MeasureUnit.FAHRENHEIT, "3.1–4.25°F" }, { 3.1, 4.25, ULocale.CHINESE, FormatWidth.WIDE, MeasureUnit.INCH, "3.1-4.25英寸" }, { 0.0, 1.0, ULocale.ENGLISH, FormatWidth.WIDE, MeasureUnit.INCH, "0–1 inches" }, { 0.0, 1.0, ULocale.ENGLISH, FormatWidth.NARROW, Currency.getInstance("EUR"), "€0.00–1.00" }, { 0.0, 1.0, ULocale.FRENCH, FormatWidth.NARROW, Currency.getInstance("EUR"), "0,00–1,00 €" }, { 0.0, 100.0, ULocale.FRENCH, FormatWidth.NARROW, Currency.getInstance("JPY"), "0–100\u00a0JPY" }, { 0.0, 1.0, ULocale.ENGLISH, FormatWidth.SHORT, Currency.getInstance("EUR"), "EUR0.00–1.00" }, { 0.0, 1.0, ULocale.FRENCH, FormatWidth.SHORT, Currency.getInstance("EUR"), "0,00–1,00\u00a0EUR" }, { 0.0, 100.0, ULocale.FRENCH, FormatWidth.SHORT, Currency.getInstance("JPY"), "0–100\u00a0JPY" }, { 0.0, 1.0, ULocale.ENGLISH, FormatWidth.WIDE, Currency.getInstance("EUR"), "0.00–1.00 euros" }, { 0.0, 1.0, ULocale.FRENCH, FormatWidth.WIDE, Currency.getInstance("EUR"), "0,00–1,00 euro" }, { 0.0, 2.0, ULocale.FRENCH, FormatWidth.WIDE, Currency.getInstance("EUR"), "0,00–2,00 euros" }, { 0.0, 100.0, ULocale.FRENCH, FormatWidth.WIDE, Currency.getInstance("JPY"), "0–100 yens japonais" } };
    int i = 0;
    for (Object[] test : tests) {
        ++i;
        double low = (Double) test[0];
        double high = (Double) test[1];
        final ULocale locale = (ULocale) test[2];
        final FormatWidth width = (FormatWidth) test[3];
        final MeasureUnit unit = (MeasureUnit) test[4];
        final Object expected = test[5];
        MeasureFormat mf = MeasureFormat.getInstance(locale, width);
        Object actual;
        try {
            actual = mf.formatMeasureRange(new Measure(low, unit), new Measure(high, unit));
        } catch (Exception e) {
            actual = e.getClass();
        }
        assertEquals(i + " Formatting unit", expected, actual);
    }
}
Also used : ULocale(android.icu.util.ULocale) MeasureUnit(android.icu.util.MeasureUnit) Measure(android.icu.util.Measure) FormatWidth(android.icu.text.MeasureFormat.FormatWidth) MeasureFormat(android.icu.text.MeasureFormat) Test(org.junit.Test)

Example 20 with MeasureFormat

use of android.icu.text.MeasureFormat in project j2objc by google.

the class NumberFormatTest method TestCurrencyFormatForMixParsing.

@Test
public void TestCurrencyFormatForMixParsing() {
    MeasureFormat curFmt = MeasureFormat.getCurrencyFormat(new ULocale("en_US"));
    String[] formats = { // string to be parsed
    "$1,234.56", "USD1,234.56", "US dollars1,234.56", "1,234.56 US dollars" };
    try {
        for (int i = 0; i < formats.length; ++i) {
            String stringToBeParsed = formats[i];
            CurrencyAmount parsedVal = (CurrencyAmount) curFmt.parseObject(stringToBeParsed);
            Number val = parsedVal.getNumber();
            if (!val.equals(new BigDecimal("1234.56"))) {
                errln("FAIL: getCurrencyFormat of default locale (en_US) failed roundtripping the number. val=" + val);
            }
            if (!parsedVal.getCurrency().equals(Currency.getInstance("USD"))) {
                errln("FAIL: getCurrencyFormat of default locale (en_US) failed roundtripping the currency");
            }
        }
    } catch (ParseException e) {
        errln("parse FAILED: " + e.toString());
    }
}
Also used : ULocale(android.icu.util.ULocale) ParseException(java.text.ParseException) MeasureFormat(android.icu.text.MeasureFormat) CurrencyAmount(android.icu.util.CurrencyAmount) BigDecimal(android.icu.math.BigDecimal) Test(org.junit.Test)

Aggregations

MeasureFormat (android.icu.text.MeasureFormat)38 Test (org.junit.Test)32 Measure (android.icu.util.Measure)26 ULocale (android.icu.util.ULocale)11 Locale (java.util.Locale)8 ArrayList (java.util.ArrayList)7 SpannableStringBuilder (android.text.SpannableStringBuilder)6 TtsSpan (android.text.style.TtsSpan)6 FormatWidth (android.icu.text.MeasureFormat.FormatWidth)5 NumberFormat (android.icu.text.NumberFormat)5 FieldPosition (java.text.FieldPosition)5 MeasureUnit (android.icu.util.MeasureUnit)4 CurrencyAmount (android.icu.util.CurrencyAmount)3 ParseException (java.text.ParseException)3 BigDecimal (android.icu.math.BigDecimal)2 IOException (java.io.IOException)2 ResourceReader (android.icu.impl.data.ResourceReader)1 TokenIterator (android.icu.impl.data.TokenIterator)1 CompactDecimalFormat (android.icu.text.CompactDecimalFormat)1 DecimalFormat (android.icu.text.DecimalFormat)1