Search in sources :

Example 36 with NumberFormat

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

the class PluralFormatUnitTest method TestApplyPatternAndFormat.

public void TestApplyPatternAndFormat() {
    // Create rules for testing.
    PluralRules oddAndEven = PluralRules.createRules("odd: n mod 2 is 1");
    {
        // Test full specified case for testing RuleSet
        PluralFormat plfOddAndEven = new PluralFormat(oddAndEven);
        plfOddAndEven.applyPattern("odd{# is odd.} other{# is even.}");
        // Test fall back to other.
        PluralFormat plfOddOrEven = new PluralFormat(oddAndEven);
        plfOddOrEven.applyPattern("other{# is odd or even.}");
        NumberFormat numberFormat = NumberFormat.getInstance(ULocale.getDefault());
        for (int i = 0; i < 22; ++i) {
            assertEquals("Fallback to other gave wrong results", numberFormat.format(i) + " is odd or even.", plfOddOrEven.format(i));
            assertEquals("Fully specified PluralFormat gave wrong results", numberFormat.format(i) + ((i % 2 == 1) ? " is odd." : " is even."), plfOddAndEven.format(i));
        }
        // ICU 4.8 does not check for duplicate keywords any more.
        PluralFormat pf = new PluralFormat(ULocale.ENGLISH, oddAndEven, "odd{foo} odd{bar} other{foobar}");
        assertEquals("should use first occurrence of the 'odd' keyword", "foo", pf.format(1));
        pf.applyPattern("odd{foo} other{bar} other{foobar}");
        assertEquals("should use first occurrence of the 'other' keyword", "bar", pf.format(2));
        // This sees the first "other" before calling the PluralSelector which then selects "other".
        pf.applyPattern("other{foo} odd{bar} other{foobar}");
        assertEquals("should use first occurrence of the 'other' keyword", "foo", pf.format(2));
    }
    // omit other keyword.
    try {
        PluralFormat plFmt = new PluralFormat(oddAndEven);
        plFmt.applyPattern("odd{foo}");
        errln("Not defining plural case other should result in an " + "exception but did not.");
    } catch (IllegalArgumentException e) {
    }
    // ICU 4.8 does not check for unknown keywords any more.
    {
        PluralFormat pf = new PluralFormat(ULocale.ENGLISH, oddAndEven, "otto{foo} other{bar}");
        assertEquals("should ignore unknown keywords", "bar", pf.format(1));
    }
    // Test invalid keyword.
    try {
        PluralFormat plFmt = new PluralFormat(oddAndEven);
        plFmt.applyPattern("*odd{foo} other{bar}");
        errln("Defining a message for an invalid keyword should result in " + "an exception but did not.");
    } catch (IllegalArgumentException e) {
    }
    // -- keyword{message1}{message2}
    try {
        PluralFormat plFmt = new PluralFormat(oddAndEven);
        plFmt.applyPattern("odd{foo},other{bar}");
        errln("Separating keyword{message} items with other characters " + "than space should provoke an exception but did not.");
    } catch (IllegalArgumentException e) {
    }
    try {
        PluralFormat plFmt = new PluralFormat(oddAndEven);
        plFmt.applyPattern("od d{foo} other{bar}");
        errln("Spaces inside keywords should provoke an exception but " + "did not.");
    } catch (IllegalArgumentException e) {
    }
    try {
        PluralFormat plFmt = new PluralFormat(oddAndEven);
        plFmt.applyPattern("odd{foo}{foobar}other{foo}");
        errln("Defining multiple messages after a keyword should provoke " + "an exception but did not.");
    } catch (IllegalArgumentException e) {
    }
    // Check that nested format is preserved.
    {
        PluralFormat plFmt = new PluralFormat(oddAndEven);
        plFmt.applyPattern("odd{The number {0, number, #.#0} is odd.}" + "other{The number {0, number, #.#0} is even.}");
        for (int i = 1; i < 3; ++i) {
            assertEquals("format did not preserve a nested format string.", ((i % 2 == 1) ? "The number {0, number, #.#0} is odd." : "The number {0, number, #.#0} is even."), plFmt.format(i));
        }
    }
    // Check that a pound sign in curly braces is preserved.
    {
        PluralFormat plFmt = new PluralFormat(oddAndEven);
        plFmt.applyPattern("odd{The number {1,number,#} is odd.}" + "other{The number {2,number,#} is even.}");
        for (int i = 1; i < 3; ++i) {
            assertEquals("format did not preserve # inside curly braces.", ((i % 2 == 1) ? "The number {1,number,#} is odd." : "The number {2,number,#} is even."), plFmt.format(i));
        }
    }
}
Also used : PluralRules(android.icu.text.PluralRules) PluralFormat(android.icu.text.PluralFormat) NumberFormat(android.icu.text.NumberFormat)

Example 37 with NumberFormat

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

the class NumberFormatTest method TestCurrencyIsoPluralFormat.

@Test
public void TestCurrencyIsoPluralFormat() {
    String[][] DATA = { // format result using PLURALCURRENCYSTYLE,
    { "en_US", "1", "USD", "$1.00", "USD1.00", "1.00 US dollars" }, { "en_US", "1234.56", "USD", "$1,234.56", "USD1,234.56", "1,234.56 US dollars" }, { "en_US", "-1234.56", "USD", "-$1,234.56", "-USD1,234.56", "-1,234.56 US dollars" }, { "zh_CN", "1", "USD", "US$1.00", "USD1.00", "1.00美元" }, { "zh_CN", "1234.56", "USD", "US$1,234.56", "USD1,234.56", "1,234.56美元" }, { "zh_CN", "1", "CNY", "¥1.00", "CNY1.00", "1.00人民币" }, { "zh_CN", "1234.56", "CNY", "¥1,234.56", "CNY1,234.56", "1,234.56人民币" }, { "ru_RU", "1", "RUB", "1,00 \u20BD", "1,00 RUB", "1,00 российского рубля" }, { "ru_RU", "2", "RUB", "2,00 \u20BD", "2,00 RUB", "2,00 российского рубля" }, { "ru_RU", "5", "RUB", "5,00 \u20BD", "5,00 RUB", "5,00 российского рубля" }, // test locale without currency information
    { "root", "-1.23", "USD", "-US$ 1.23", "-USD 1.23", "-1.23 USD" }, // ensure that the root locale is still used with modifiers
    { "root@numbers=latn", "-1.23", "USD", "-US$ 1.23", "-USD 1.23", "-1.23 USD" }, // ensure that the root locale is still used with modifiers
    { "root@numbers=arab", "-1.23", "USD", "\u061C-\u0661\u066B\u0662\u0663\u00A0US$", "\u061C-\u0661\u066B\u0662\u0663\u00A0USD", "\u061C-\u0661\u066B\u0662\u0663 USD" }, { "es_AR", "1", "INR", "INR\u00A01,00", "INR\u00A01,00", "1,00 rupia india" }, { "ar_EG", "1", "USD", "١٫٠٠\u00A0US$", "١٫٠٠\u00A0USD", "١٫٠٠ دولار أمريكي" } };
    for (int i = 0; i < DATA.length; ++i) {
        for (int k = NumberFormat.CURRENCYSTYLE; k <= NumberFormat.PLURALCURRENCYSTYLE; ++k) {
            // k represents currency format style.
            if (k != NumberFormat.CURRENCYSTYLE && k != NumberFormat.ISOCURRENCYSTYLE && k != NumberFormat.PLURALCURRENCYSTYLE) {
                continue;
            }
            String localeString = DATA[i][0];
            Double numberToBeFormat = new Double(DATA[i][1]);
            String currencyISOCode = DATA[i][2];
            ULocale locale = new ULocale(localeString);
            NumberFormat numFmt = NumberFormat.getInstance(locale, k);
            numFmt.setCurrency(Currency.getInstance(currencyISOCode));
            String strBuf = numFmt.format(numberToBeFormat);
            int resultDataIndex = k - 1;
            if (k == NumberFormat.CURRENCYSTYLE) {
                resultDataIndex = k + 2;
            }
            // DATA[i][resultDataIndex] is the currency format result
            // using 'k' currency style.
            String formatResult = DATA[i][resultDataIndex];
            if (!strBuf.equals(formatResult)) {
                errln("FAIL: localeID: " + localeString + ", expected(" + formatResult.length() + "): \"" + formatResult + "\", actual(" + strBuf.length() + "): \"" + strBuf + "\"");
            }
            try {
                // test parsing, and test parsing for all currency formats.
                for (int j = 3; j < 6; ++j) {
                    // DATA[i][3] is the currency format result using
                    // CURRENCYSTYLE formatter.
                    // DATA[i][4] is the currency format result using
                    // ISOCURRENCYSTYLE formatter.
                    // DATA[i][5] is the currency format result using
                    // PLURALCURRENCYSTYLE formatter.
                    String oneCurrencyFormatResult = DATA[i][j];
                    Number val = numFmt.parse(oneCurrencyFormatResult);
                    if (val.doubleValue() != numberToBeFormat.doubleValue()) {
                        errln("FAIL: getCurrencyFormat of locale " + localeString + " failed roundtripping the number. val=" + val + "; expected: " + numberToBeFormat);
                    }
                }
            } catch (ParseException e) {
                errln("FAIL: " + e.getMessage());
            }
        }
    }
}
Also used : ULocale(android.icu.util.ULocale) ParseException(java.text.ParseException) RuleBasedNumberFormat(android.icu.text.RuleBasedNumberFormat) NumberFormat(android.icu.text.NumberFormat) Test(org.junit.Test)

Example 38 with NumberFormat

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

the class NumberFormatTest method TestJB3832.

@Test
public void TestJB3832() {
    ULocale locale = new ULocale("pt_PT@currency=PTE");
    NumberFormat format = NumberFormat.getCurrencyInstance(locale);
    Currency curr = Currency.getInstance(locale);
    logln("\nName of the currency is: " + curr.getName(locale, Currency.LONG_NAME, new boolean[] { false }));
    CurrencyAmount cAmt = new CurrencyAmount(1150.50, curr);
    // cover hashCode
    logln("CurrencyAmount object's hashCode is: " + cAmt.hashCode());
    String str = format.format(cAmt);
    String expected = "1,150$50\u00a0\u200b";
    if (!expected.equals(str)) {
        errln("Did not get the expected output Expected: " + expected + " Got: " + str);
    }
}
Also used : ULocale(android.icu.util.ULocale) Currency(android.icu.util.Currency) CurrencyAmount(android.icu.util.CurrencyAmount) RuleBasedNumberFormat(android.icu.text.RuleBasedNumberFormat) NumberFormat(android.icu.text.NumberFormat) Test(org.junit.Test)

Example 39 with NumberFormat

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

the class MyNumberFormat method Test4185761.

@Test
public void Test4185761() throws IOException, ClassNotFoundException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    NumberFormat nf = NumberFormat.getInstance(Locale.US);
    // Set special values we are going to search for in the output byte stream
    // These are all legal values.
    // Keep under 309
    nf.setMinimumIntegerDigits(0x111);
    // Keep under 309
    nf.setMaximumIntegerDigits(0x112);
    // Keep under 340
    nf.setMinimumFractionDigits(0x113);
    // Keep under 340
    nf.setMaximumFractionDigits(0x114);
    oos.writeObject(nf);
    oos.flush();
    baos.close();
    byte[] bytes = baos.toByteArray();
    // Scan for locations of min/max int/fract values in the byte array.
    // At the moment (ICU4J 2.1), there is only one instance of each target pair
    // in the byte stream, so assume first match is it.  Note this is not entirely
    // failsafe, and needs to be checked if we change the package or structure of
    // this class.
    // Current positions are 890, 880, 886, 876
    int[] offsets = new int[4];
    for (int i = 0; i < bytes.length - 1; ++i) {
        if (bytes[i] == 0x01) {
            // high byte
            for (int j = 0; j < offsets.length; ++j) {
                if ((offsets[j] == 0) && (bytes[i + 1] == (0x11 + j))) {
                    // low byte
                    offsets[j] = i;
                    break;
                }
            }
        }
    }
    {
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
        Object o = ois.readObject();
        ois.close();
        if (!nf.equals(o)) {
            errln("Fail: NumberFormat serialization/equality bug");
        } else {
            logln("NumberFormat serialization/equality is OKAY.");
        }
    }
    // Numberformat should catch this and throw an exception.
    for (int i = 0; i < offsets.length; ++i) {
        bytes[offsets[i]] = (byte) (4 - i);
    }
    {
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
        try {
            NumberFormat format = (NumberFormat) ois.readObject();
            // fix "The variable is never used"
            logln("format: " + format.format(1234.56));
            errln("FAIL: Deserialized bogus NumberFormat with minXDigits > maxXDigits");
        } catch (InvalidObjectException e) {
            logln("Ok: " + e.getMessage());
        }
    }
    // (for compatibility with versions streamed out before the maximums were imposed).
    for (int i = 0; i < offsets.length; ++i) {
        bytes[offsets[i]] = 4;
    }
    // Android patch (http://b/27855939) start.
    // Allow 2 billion integer digits.
    bytes[offsets[1] - 2] = 127;
    {
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
        NumberFormat format = (NumberFormat) ois.readObject();
        // For compatibility with previous version
        if ((format.getMaximumIntegerDigits() != 2000000000) || format.getMaximumFractionDigits() != 340) {
            // Android patch (http://b/27855939) end.
            errln("FAIL: Deserialized bogus NumberFormat with values out of range," + " intMin: " + format.getMinimumIntegerDigits() + " intMax: " + format.getMaximumIntegerDigits() + " fracMin: " + format.getMinimumFractionDigits() + " fracMax: " + format.getMaximumFractionDigits());
        } else {
            logln("Ok: Digit count out of range");
        }
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InvalidObjectException(java.io.InvalidObjectException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ObjectOutputStream(java.io.ObjectOutputStream) NumberFormat(android.icu.text.NumberFormat) ObjectInputStream(java.io.ObjectInputStream) Test(org.junit.Test)

Example 40 with NumberFormat

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

the class NumberFormatRegressionTest method TestJ691.

/**
 * DateFormat should call setIntegerParseOnly(TRUE) on adopted
 * NumberFormat objects.
 */
@Test
public void TestJ691() {
    Locale loc = new Locale("fr", "CH");
    // set up the input date string & expected output
    String udt = "11.10.2000";
    String exp = "11.10.00";
    // create a Calendar for this locale
    Calendar cal = Calendar.getInstance(loc);
    // create a NumberFormat for this locale
    NumberFormat nf = NumberFormat.getInstance(loc);
    // *** Here's the key: We don't want to have to do THIS:
    // nf.setParseIntegerOnly(true);
    // create the DateFormat
    DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, loc);
    df.setCalendar(cal);
    df.setNumberFormat(nf);
    // set parsing to lenient & parse
    Date ulocdat = new Date();
    df.setLenient(true);
    try {
        ulocdat = df.parse(udt);
    } catch (java.text.ParseException pe) {
        errln(pe.getMessage());
    }
    // format back to a string
    String outString = df.format(ulocdat);
    if (!outString.equals(exp)) {
        errln("FAIL: " + udt + " => " + outString);
    }
}
Also used : ULocale(android.icu.util.ULocale) Locale(java.util.Locale) Calendar(android.icu.util.Calendar) DateFormat(android.icu.text.DateFormat) ParseException(java.text.ParseException) Date(java.util.Date) 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