Search in sources :

Example 6 with CurrencyAmount

use of android.icu.util.CurrencyAmount 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 7 with CurrencyAmount

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

the class NumberFormatTest method expectParseCurrency.

private void expectParseCurrency(NumberFormat fmt, Currency expected, String text) {
    ParsePosition pos = new ParsePosition(0);
    CurrencyAmount currencyAmount = fmt.parseCurrency(text, pos);
    assertTrue("Parse of " + text + " should have succeeded.", pos.getIndex() > 0);
    assertEquals("Currency should be correct.", expected, currencyAmount.getCurrency());
}
Also used : CurrencyAmount(android.icu.util.CurrencyAmount) ParsePosition(java.text.ParsePosition)

Example 8 with CurrencyAmount

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

the class DecimalFormat method parse.

/**
 * Parses the given text as either a Number or a CurrencyAmount.
 *
 * @param text the string to parse
 * @param parsePosition input-output position; on input, the position within text to
 * match; must have 0 <= pos.getIndex() < text.length(); on output, the position after
 * the last matched character. If the parse fails, the position in unchanged upon
 * output.
 * @param currency if non-null, a CurrencyAmount is parsed and returned; otherwise a
 * Number is parsed and returned
 * @return a Number or CurrencyAmount or null
 */
private Object parse(String text, ParsePosition parsePosition, Currency[] currency) {
    int backup;
    int i = backup = parsePosition.getIndex();
    // Skip padding characters, if around prefix
    if (formatWidth > 0 && (padPosition == PAD_BEFORE_PREFIX || padPosition == PAD_AFTER_PREFIX)) {
        i = skipPadding(text, i);
    }
    if (text.regionMatches(i, symbols.getNaN(), 0, symbols.getNaN().length())) {
        i += symbols.getNaN().length();
        // Skip padding characters, if around suffix
        if (formatWidth > 0 && (padPosition == PAD_BEFORE_SUFFIX || padPosition == PAD_AFTER_SUFFIX)) {
            i = skipPadding(text, i);
        }
        parsePosition.setIndex(i);
        return new Double(Double.NaN);
    }
    // NaN parse failed; start over
    i = backup;
    boolean[] status = new boolean[STATUS_LENGTH];
    if (currencySignCount != CURRENCY_SIGN_COUNT_ZERO) {
        if (!parseForCurrency(text, parsePosition, currency, status)) {
            return null;
        }
    } else if (currency != null) {
        return null;
    } else {
        if (!subparse(text, parsePosition, digitList, status, currency, negPrefixPattern, negSuffixPattern, posPrefixPattern, posSuffixPattern, false, Currency.SYMBOL_NAME)) {
            parsePosition.setIndex(backup);
            return null;
        }
    }
    Number n = null;
    // Handle infinity
    if (status[STATUS_INFINITE]) {
        n = new Double(status[STATUS_POSITIVE] ? Double.POSITIVE_INFINITY : Double.NEGATIVE_INFINITY);
    } else // Handle underflow
    if (status[STATUS_UNDERFLOW]) {
        n = status[STATUS_POSITIVE] ? new Double("0.0") : new Double("-0.0");
    } else // Handle -0.0
    if (!status[STATUS_POSITIVE] && digitList.isZero()) {
        n = new Double("-0.0");
    } else {
        // Do as much of the multiplier conversion as possible without
        // losing accuracy.
        // Don't modify this.multiplier
        int mult = multiplier;
        while (mult % 10 == 0) {
            --digitList.decimalAt;
            mult /= 10;
        }
        // Handle integral values
        if (!parseBigDecimal && mult == 1 && digitList.isIntegral()) {
            // hack quick long
            if (digitList.decimalAt < 12) {
                // quick check for long
                long l = 0;
                if (digitList.count > 0) {
                    int nx = 0;
                    while (nx < digitList.count) {
                        l = l * 10 + (char) digitList.digits[nx++] - '0';
                    }
                    while (nx++ < digitList.decimalAt) {
                        l *= 10;
                    }
                    if (!status[STATUS_POSITIVE]) {
                        l = -l;
                    }
                }
                n = Long.valueOf(l);
            } else {
                BigInteger big = digitList.getBigInteger(status[STATUS_POSITIVE]);
                n = (big.bitLength() < 64) ? (Number) Long.valueOf(big.longValue()) : (Number) big;
            }
        } else // Handle non-integral values or the case where parseBigDecimal is set
        {
            BigDecimal big = digitList.getBigDecimalICU(status[STATUS_POSITIVE]);
            n = big;
            if (mult != 1) {
                n = big.divide(BigDecimal.valueOf(mult), mathContext);
            }
        }
    }
    // Assemble into CurrencyAmount if necessary
    return (currency != null) ? (Object) new CurrencyAmount(n, currency[0]) : (Object) n;
}
Also used : BigInteger(java.math.BigInteger) BigDecimal(android.icu.math.BigDecimal) CurrencyAmount(android.icu.util.CurrencyAmount)

Example 9 with CurrencyAmount

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

the class CurrencyFormat method format.

/**
 * Override Format.format().
 * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
 */
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
    if (!(obj instanceof CurrencyAmount)) {
        throw new IllegalArgumentException("Invalid type: " + obj.getClass().getName());
    }
    CurrencyAmount currency = (CurrencyAmount) obj;
    fmt.setCurrency(currency.getCurrency());
    return fmt.format(currency.getNumber(), toAppendTo, pos);
}
Also used : CurrencyAmount(android.icu.util.CurrencyAmount)

Example 10 with CurrencyAmount

use of android.icu.util.CurrencyAmount 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)

Aggregations

CurrencyAmount (android.icu.util.CurrencyAmount)14 Test (org.junit.Test)10 ULocale (android.icu.util.ULocale)8 ParseException (java.text.ParseException)5 BigDecimal (android.icu.math.BigDecimal)4 CompactDecimalFormat (android.icu.text.CompactDecimalFormat)4 NumberFormat (android.icu.text.NumberFormat)4 RuleBasedNumberFormat (android.icu.text.RuleBasedNumberFormat)4 MeasureFormat (android.icu.text.MeasureFormat)3 Currency (android.icu.util.Currency)3 IOException (java.io.IOException)3 BigInteger (java.math.BigInteger)3 ParsePosition (java.text.ParsePosition)2 Locale (java.util.Locale)2 StandardPlural (android.icu.impl.StandardPlural)1 ResourceReader (android.icu.impl.data.ResourceReader)1 TokenIterator (android.icu.impl.data.TokenIterator)1 DecimalFormat (android.icu.text.DecimalFormat)1 DecimalFormatSymbols (android.icu.text.DecimalFormatSymbols)1 MeasureUnit (android.icu.util.MeasureUnit)1