Search in sources :

Example 11 with NumberFormat

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

the class ZoneMeta method parseCustomID.

/*
     * Parses the given custom time zone identifier
     * @param id id A string of the form GMT[+-]hh:mm, GMT[+-]hhmm, or
     * GMT[+-]hh.
     * @param fields An array of int (length = 4) to receive the parsed
     * offset time fields.  The sign is set to fields[0] (-1 or 1),
     * hour is set to fields[1], minute is set to fields[2] and second is
     * set to fields[3].
     * @return Returns true when the given custom id is valid.
     */
static boolean parseCustomID(String id, int[] fields) {
    NumberFormat numberFormat = null;
    if (id != null && id.length() > kGMT_ID.length() && id.toUpperCase(Locale.ENGLISH).startsWith(kGMT_ID)) {
        ParsePosition pos = new ParsePosition(kGMT_ID.length());
        int sign = 1;
        int hour = 0;
        int min = 0;
        int sec = 0;
        if (id.charAt(pos.getIndex()) == 0x002D) /*'-'*/
        {
            sign = -1;
        } else if (id.charAt(pos.getIndex()) != 0x002B) /*'+'*/
        {
            return false;
        }
        pos.setIndex(pos.getIndex() + 1);
        numberFormat = NumberFormat.getInstance();
        numberFormat.setParseIntegerOnly(true);
        // Look for either hh:mm, hhmm, or hh
        int start = pos.getIndex();
        Number n = numberFormat.parse(id, pos);
        if (pos.getIndex() == start) {
            return false;
        }
        hour = n.intValue();
        if (pos.getIndex() < id.length()) {
            if (pos.getIndex() - start > 2 || id.charAt(pos.getIndex()) != 0x003A) /*':'*/
            {
                return false;
            }
            // hh:mm
            pos.setIndex(pos.getIndex() + 1);
            int oldPos = pos.getIndex();
            n = numberFormat.parse(id, pos);
            if ((pos.getIndex() - oldPos) != 2) {
                // must be 2 digits
                return false;
            }
            min = n.intValue();
            if (pos.getIndex() < id.length()) {
                if (id.charAt(pos.getIndex()) != 0x003A) /*':'*/
                {
                    return false;
                }
                // [:ss]
                pos.setIndex(pos.getIndex() + 1);
                oldPos = pos.getIndex();
                n = numberFormat.parse(id, pos);
                if (pos.getIndex() != id.length() || (pos.getIndex() - oldPos) != 2) {
                    return false;
                }
                sec = n.intValue();
            }
        } else {
            // Supported formats are below -
            // 
            // HHmmss
            // Hmmss
            // HHmm
            // Hmm
            // HH
            // H
            int length = pos.getIndex() - start;
            if (length <= 0 || 6 < length) {
                // invalid length
                return false;
            }
            switch(length) {
                case 1:
                case 2:
                    // already set to hour
                    break;
                case 3:
                case 4:
                    min = hour % 100;
                    hour /= 100;
                    break;
                case 5:
                case 6:
                    sec = hour % 100;
                    min = (hour / 100) % 100;
                    hour /= 10000;
                    break;
            }
        }
        if (hour <= kMAX_CUSTOM_HOUR && min <= kMAX_CUSTOM_MIN && sec <= kMAX_CUSTOM_SEC) {
            if (fields != null) {
                if (fields.length >= 1) {
                    fields[0] = sign;
                }
                if (fields.length >= 2) {
                    fields[1] = hour;
                }
                if (fields.length >= 3) {
                    fields[2] = min;
                }
                if (fields.length >= 4) {
                    fields[3] = sec;
                }
            }
            return true;
        }
    }
    return false;
}
Also used : NumberFormat(android.icu.text.NumberFormat) ParsePosition(java.text.ParsePosition)

Example 12 with NumberFormat

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

the class GlobalizationPreferencesTest method TestNumberFormat.

@Test
public void TestNumberFormat() {
    GlobalizationPreferences gp = new GlobalizationPreferences();
    NumberFormat nf;
    String numStr;
    double num = 123456.789;
    // Set unsupported locale with supported territory ang_KR
    logln("Set locale - ang_KR");
    gp.setLocale(new ULocale("ang_KR"));
    nf = gp.getNumberFormat(GlobalizationPreferences.NF_CURRENCY);
    numStr = nf.format(num);
    if (!numStr.equals("\u20a9\u00a0123,457")) {
        errln("FAIL: Number string is " + numStr + " Expected: \u20a9\u00a0123,457");
    }
    // Set locale - de_DE
    logln("Set locale - de_DE");
    gp.setLocale(new ULocale("de_DE"));
    // NF_NUMBER
    logln("NUMBER type");
    nf = gp.getNumberFormat(GlobalizationPreferences.NF_NUMBER);
    numStr = nf.format(num);
    if (!numStr.equals("123.456,789")) {
        errln("FAIL: Number string is " + numStr + " Expected: 123.456,789");
    }
    // NF_CURRENCY
    logln("CURRENCY type");
    nf = gp.getNumberFormat(GlobalizationPreferences.NF_CURRENCY);
    numStr = nf.format(num);
    if (!numStr.equals("123.456,79\u00a0\u20AC")) {
        errln("FAIL: Number string is " + numStr + " Expected: 123.456,79\u00a0\u20AC");
    }
    // NF_PERCENT
    logln("PERCENT type");
    nf = gp.getNumberFormat(GlobalizationPreferences.NF_PERCENT);
    numStr = nf.format(num);
    if (!numStr.equals("12.345.679\u00a0%")) {
        errln("FAIL: Number string is " + numStr + " Expected: 12.345.679\u00a0%");
    }
    // NF_SCIENTIFIC
    logln("SCIENTIFIC type");
    nf = gp.getNumberFormat(GlobalizationPreferences.NF_SCIENTIFIC);
    numStr = nf.format(num);
    if (!numStr.equals("1,23456789E5")) {
        errln("FAIL: Number string is " + numStr + " Expected: 1,23456789E5");
    }
    // NF_INTEGER
    logln("INTEGER type");
    nf = gp.getNumberFormat(GlobalizationPreferences.NF_INTEGER);
    numStr = nf.format(num);
    if (!numStr.equals("123.457")) {
        errln("FAIL: Number string is " + numStr + " Expected: 123.457");
    }
    // Invalid number type
    logln("INVALID type");
    boolean illegalArg = false;
    try {
        nf = gp.getNumberFormat(100);
    } catch (IllegalArgumentException iae) {
        logln("Illegal number format type 100");
        illegalArg = true;
    }
    if (!illegalArg) {
        errln("FAIL: getNumberFormat must throw IllegalArgumentException for type 100");
    }
    illegalArg = false;
    try {
        nf = gp.getNumberFormat(-1);
    } catch (IllegalArgumentException iae) {
        logln("Illegal number format type -1");
        illegalArg = true;
    }
    if (!illegalArg) {
        errln("FAIL: getNumberFormat must throw IllegalArgumentException for type -1");
    }
    // Set explicit territory
    logln("Set territory - US");
    gp.setTerritory("US");
    nf = gp.getNumberFormat(GlobalizationPreferences.NF_CURRENCY);
    numStr = nf.format(num);
    if (!numStr.equals("123.456,79\u00a0$")) {
        errln("FAIL: Number string is " + numStr + " Expected: 123.456,79\u00a0$");
    }
    // Set explicit currency
    logln("Set currency - GBP");
    gp.setCurrency(Currency.getInstance("GBP"));
    nf = gp.getNumberFormat(GlobalizationPreferences.NF_CURRENCY);
    numStr = nf.format(num);
    if (!numStr.equals("123.456,79\u00a0\u00A3")) {
        errln("FAIL: Number string is " + numStr + " Expected: 123.456,79\u00a0\u00A3");
    }
    // Set exliplicit NumberFormat
    logln("Set explicit NumberFormat objects");
    NumberFormat customNum = NumberFormat.getNumberInstance(new ULocale("he_IL"));
    gp.setNumberFormat(GlobalizationPreferences.NF_NUMBER, customNum);
    NumberFormat customCur = NumberFormat.getCurrencyInstance(new ULocale("zh_CN"));
    gp.setNumberFormat(GlobalizationPreferences.NF_CURRENCY, customCur);
    NumberFormat customPct = NumberFormat.getPercentInstance(new ULocale("el_GR"));
    gp.setNumberFormat(GlobalizationPreferences.NF_PERCENT, customPct);
    NumberFormat customSci = NumberFormat.getScientificInstance(new ULocale("ru_RU"));
    gp.setNumberFormat(GlobalizationPreferences.NF_SCIENTIFIC, customSci);
    NumberFormat customInt = NumberFormat.getIntegerInstance(new ULocale("pt_PT"));
    gp.setNumberFormat(GlobalizationPreferences.NF_INTEGER, customInt);
    nf = gp.getNumberFormat(GlobalizationPreferences.NF_NUMBER);
    if (!nf.getLocale(ULocale.VALID_LOCALE).toString().equals("he_IL")) {
        errln("FAIL: The NumberFormat instance must use locale he_IL");
    }
    nf = gp.getNumberFormat(GlobalizationPreferences.NF_CURRENCY);
    if (!nf.getLocale(ULocale.VALID_LOCALE).toString().equals("zh_CN")) {
        errln("FAIL: The NumberFormat instance must use locale zh_CN");
    }
    nf = gp.getNumberFormat(GlobalizationPreferences.NF_PERCENT);
    if (!nf.getLocale(ULocale.VALID_LOCALE).toString().equals("el_GR")) {
        errln("FAIL: The NumberFormat instance must use locale el_GR");
    }
    nf = gp.getNumberFormat(GlobalizationPreferences.NF_SCIENTIFIC);
    if (!nf.getLocale(ULocale.VALID_LOCALE).toString().equals("ru_RU")) {
        errln("FAIL: The NumberFormat instance must use locale ru_RU");
    }
    nf = gp.getNumberFormat(GlobalizationPreferences.NF_INTEGER);
    if (!nf.getLocale(ULocale.VALID_LOCALE).toString().equals("pt_PT")) {
        errln("FAIL: The NumberFormat instance must use locale pt_PT");
    }
    NumberFormat customNum1 = NumberFormat.getNumberInstance(new ULocale("hi_IN"));
    // Freeze
    logln("Freeze this object");
    boolean isFrozen = false;
    gp.freeze();
    try {
        gp.setNumberFormat(GlobalizationPreferences.NF_NUMBER, customNum1);
    } catch (UnsupportedOperationException uoe) {
        logln("setNumberFormat is blocked");
        isFrozen = true;
    }
    if (!isFrozen) {
        errln("FAIL: setNumberFormat must be blocked after frozen");
    }
    // Create a modifiable clone
    GlobalizationPreferences gp1 = (GlobalizationPreferences) gp.cloneAsThawed();
    // Number type format's locale is still he_IL
    nf = gp1.getNumberFormat(GlobalizationPreferences.NF_NUMBER);
    if (!nf.getLocale(ULocale.VALID_LOCALE).toString().equals("he_IL")) {
        errln("FAIL: The NumberFormat instance must use locale he_IL");
    }
    logln("Set custom number format using locale hi_IN");
    gp1.setNumberFormat(GlobalizationPreferences.NF_NUMBER, customNum1);
    nf = gp1.getNumberFormat(GlobalizationPreferences.NF_NUMBER);
    if (!nf.getLocale(ULocale.VALID_LOCALE).toString().equals("hi_IN")) {
        errln("FAIL: The NumberFormat instance must use locale hi_IN");
    }
}
Also used : GlobalizationPreferences(android.icu.util.GlobalizationPreferences) ULocale(android.icu.util.ULocale) NumberFormat(android.icu.text.NumberFormat) Test(org.junit.Test)

Example 13 with NumberFormat

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

the class IntlTestDateFormatAPI method TestAPI.

// This test checks various generic API methods in DateFormat to achieve 100% API coverage.
@Test
public void TestAPI() {
    logln("DateFormat API test---");
    logln("");
    Locale.setDefault(Locale.ENGLISH);
    // ======= Test constructors
    logln("Testing DateFormat constructors");
    DateFormat def = DateFormat.getInstance();
    DateFormat fr = DateFormat.getTimeInstance(DateFormat.FULL, Locale.FRENCH);
    DateFormat it = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.ITALIAN);
    DateFormat de = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.GERMAN);
    // ======= Test equality
    logln("Testing equality operator");
    if (fr.equals(it)) {
        errln("ERROR: equals failed");
    }
    // ======= Test various format() methods
    logln("Testing various format() methods");
    Date d = new Date((long) 837039928046.0);
    StringBuffer res1 = new StringBuffer();
    StringBuffer res2 = new StringBuffer();
    String res3 = new String();
    FieldPosition pos1 = new FieldPosition(0);
    FieldPosition pos2 = new FieldPosition(0);
    res1 = fr.format(d, res1, pos1);
    logln("" + d.getTime() + " formatted to " + res1);
    res2 = it.format(d, res2, pos2);
    logln("" + d.getTime() + " formatted to " + res2);
    res3 = de.format(d);
    logln("" + d.getTime() + " formatted to " + res3);
    // ======= Test parse()
    logln("Testing parse()");
    String text = new String("02/03/76, 2:50 AM, CST");
    Object result1 = new Date();
    Date result2 = new Date();
    Date result3 = new Date();
    ParsePosition pos = new ParsePosition(0);
    ParsePosition pos01 = new ParsePosition(0);
    result1 = def.parseObject(text, pos);
    if (result1 == null) {
        errln("ERROR: parseObject() failed for " + text);
    }
    logln(text + " parsed into " + ((Date) result1).getTime());
    try {
        result2 = def.parse(text);
    } catch (ParseException e) {
        errln("ERROR: parse() failed");
    }
    logln(text + " parsed into " + result2.getTime());
    result3 = def.parse(text, pos01);
    if (result3 == null) {
        errln("ERROR: parse() failed for " + text);
    }
    logln(text + " parsed into " + result3.getTime());
    // ======= Test getters and setters
    logln("Testing getters and setters");
    final Locale[] locales = DateFormat.getAvailableLocales();
    long count = locales.length;
    logln("Got " + count + " locales");
    // Ticket #6280, #8078 and #11674
    // These locales should be included in the result
    boolean missingLocaleNotFatal = TestUtil.getJavaVendor() == JavaVendor.Android || TestUtil.getJavaVersion() >= 7;
    final Locale[] samples = { new Locale("zh", "CN"), new Locale("zh", "TW"), new Locale("zh", "HK"), new Locale("sr", "RS") };
    boolean[] available = new boolean[samples.length];
    for (int i = 0; i < count; i++) {
        String name;
        name = locales[i].getDisplayName();
        logln(name);
        for (int j = 0; j < samples.length; j++) {
            if (locales[i].equals(samples[j])) {
                available[j] = true;
                break;
            }
        }
    }
    for (int i = 0; i < available.length; i++) {
        if (!available[i]) {
            if (missingLocaleNotFatal) {
                // Java 7 supports script field, so zh_Hans_CN is included
                // in the available locale list.
                logln("INFO: missing Locale: " + samples[i]);
            } else {
                errln("ERROR: missing Locale: " + samples[i]);
            }
        }
    }
    fr.setLenient(it.isLenient());
    if (fr.isLenient() != it.isLenient()) {
        errln("ERROR: setLenient() failed");
    }
    final Calendar cal = def.getCalendar();
    Calendar newCal = (Calendar) cal.clone();
    de.setCalendar(newCal);
    it.setCalendar(newCal);
    if (!de.getCalendar().equals(it.getCalendar())) {
        errln("ERROR: set Calendar() failed");
    }
    final NumberFormat nf = def.getNumberFormat();
    NumberFormat newNf = (NumberFormat) nf.clone();
    de.setNumberFormat(newNf);
    it.setNumberFormat(newNf);
    if (!de.getNumberFormat().equals(it.getNumberFormat())) {
        errln("ERROR: set NumberFormat() failed");
    }
    final TimeZone tz = def.getTimeZone();
    TimeZone newTz = (TimeZone) tz.clone();
    de.setTimeZone(newTz);
    it.setTimeZone(newTz);
    if (!de.getTimeZone().equals(it.getTimeZone())) {
        errln("ERROR: set TimeZone() failed");
    }
// ======= Test getStaticClassID()
// logln("Testing instanceof()");
// try {
// DateFormat test = new SimpleDateFormat();
// if (! (test instanceof SimpleDateFormat)) {
// errln("ERROR: instanceof failed");
// }
// }
// catch (Exception e) {
// errln("ERROR: Couldn't create a DateFormat");
// }
}
Also used : Locale(java.util.Locale) Calendar(android.icu.util.Calendar) FieldPosition(java.text.FieldPosition) Date(java.util.Date) TimeZone(android.icu.util.TimeZone) DateFormat(android.icu.text.DateFormat) ParseException(java.text.ParseException) ParsePosition(java.text.ParsePosition) NumberFormat(android.icu.text.NumberFormat) Test(org.junit.Test)

Example 14 with NumberFormat

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

the class MeasureUnitTest method testDoubleZero.

@Test
public void testDoubleZero() {
    ULocale en = new ULocale("en");
    NumberFormat nf = NumberFormat.getInstance(en);
    nf.setMinimumFractionDigits(2);
    nf.setMaximumFractionDigits(2);
    MeasureFormat mf = MeasureFormat.getInstance(en, FormatWidth.WIDE, nf);
    assertEquals("Positive Rounding", "4 hours, 23 minutes, 16.00 seconds", mf.formatMeasures(new Measure(4.7, MeasureUnit.HOUR), new Measure(23, MeasureUnit.MINUTE), new Measure(16, MeasureUnit.SECOND)));
    assertEquals("Negative Rounding", "-4 hours, 23 minutes, 16.00 seconds", mf.formatMeasures(new Measure(-4.7, MeasureUnit.HOUR), new Measure(23, MeasureUnit.MINUTE), new Measure(16, MeasureUnit.SECOND)));
}
Also used : ULocale(android.icu.util.ULocale) Measure(android.icu.util.Measure) MeasureFormat(android.icu.text.MeasureFormat) NumberFormat(android.icu.text.NumberFormat) Test(org.junit.Test)

Example 15 with NumberFormat

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

the class MeasureUnitTest method Test10219FractionalPlurals.

@Test
public void Test10219FractionalPlurals() {
    double[] values = { 1.588, 1.011 };
    String[][] expected = { { "1 minute", "1.5 minutes", "1.58 minutes" }, { "1 minute", "1.0 minutes", "1.01 minutes" } };
    for (int j = 0; j < values.length; j++) {
        for (int i = 0; i < expected[j].length; i++) {
            NumberFormat nf = NumberFormat.getNumberInstance(ULocale.ENGLISH);
            nf.setRoundingMode(BigDecimal.ROUND_DOWN);
            nf.setMinimumFractionDigits(i);
            nf.setMaximumFractionDigits(i);
            MeasureFormat mf = MeasureFormat.getInstance(ULocale.ENGLISH, FormatWidth.WIDE, nf);
            assertEquals("Test10219", expected[j][i], mf.format(new Measure(values[j], MeasureUnit.MINUTE)));
        }
    }
}
Also used : Measure(android.icu.util.Measure) MeasureFormat(android.icu.text.MeasureFormat) NumberFormat(android.icu.text.NumberFormat) Test(org.junit.Test)

Aggregations

NumberFormat (android.icu.text.NumberFormat)105 Test (org.junit.Test)84 ULocale (android.icu.util.ULocale)39 RuleBasedNumberFormat (android.icu.text.RuleBasedNumberFormat)35 DecimalFormat (android.icu.text.DecimalFormat)27 Locale (java.util.Locale)24 ParseException (java.text.ParseException)20 ParsePosition (java.text.ParsePosition)13 DecimalFormatSymbols (android.icu.text.DecimalFormatSymbols)12 CompactDecimalFormat (android.icu.text.CompactDecimalFormat)11 FieldPosition (java.text.FieldPosition)9 IOException (java.io.IOException)7 DateFormat (android.icu.text.DateFormat)5 Calendar (android.icu.util.Calendar)5 Date (java.util.Date)5 BigDecimal (android.icu.math.BigDecimal)4 DisplayContext (android.icu.text.DisplayContext)4 MeasureFormat (android.icu.text.MeasureFormat)4 SimpleDateFormat (android.icu.text.SimpleDateFormat)4 PluralFormat (android.icu.text.PluralFormat)3