Java Code Examples for android.icu.text.NumberFormat#format()

The following examples show how to use android.icu.text.NumberFormat#format() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NumberRegressionTests.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * DecimalFormat formats 1.001 to "1.00" instead of "1" with 2 fraction
 * digits.
 */
@Test
public void Test4217661() {
    Object[] DATA = {
        new Double(0.001), "0",
        new Double(1.001), "1",
        new Double(0.006), "0.01",
        new Double(1.006), "1.01",
    };
    NumberFormat fmt = NumberFormat.getInstance(Locale.US);
    fmt.setMaximumFractionDigits(2); 
    for (int i=0; i<DATA.length; i+=2) {
        String s = fmt.format(((Double) DATA[i]).doubleValue());
        if (!s.equals(DATA[i+1])) {
            errln("FAIL: Got " + s + ", exp " + DATA[i+1]); 
        }
    }
}
 
Example 2
Source File: NumberRegressionTests.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * NumberFormat does not parse negative zero.
 */
@Test
public void Test4162852() throws ParseException {
    for (int i=0; i<2; ++i) {
        NumberFormat f = (i == 0) ? NumberFormat.getInstance()
            : NumberFormat.getPercentInstance();
        double d = -0.0;
        String s = f.format(d);
        double e = f.parse(s).doubleValue();
        logln("" +
              d + " -> " +
              '"' + s + '"' + " -> " +
          e);
        if (e != 0.0 || 1.0/e > 0.0) {
            logln("Failed to parse negative zero");
        }
    }
}
 
Example 3
Source File: NumberRegressionTests.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * NumberFormat cannot format Double.MAX_VALUE
 */
@Test
public void Test4162198() {
    double dbl = Double.MAX_VALUE;
    NumberFormat f = NumberFormat.getInstance();
    f.setMaximumFractionDigits(Integer.MAX_VALUE);
    f.setMaximumIntegerDigits(Integer.MAX_VALUE);
    String s = f.format(dbl);
    logln("The number " + dbl + " formatted to " + s);
    Number n = null;
    try {
        n = f.parse(s);
    } catch (java.text.ParseException e) {
        errln("Caught a ParseException:");
        e.printStackTrace();
    }
    logln("The string " + s + " parsed as " + n);
    if (n.doubleValue() != dbl) {
        errln("Round trip failure");
    }
}
 
Example 4
Source File: NumberFormatRegressionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void TestSerialization() throws IOException{
    byte[][] contents = NumberFormatSerialTestData.getContent();
    double data = 1234.56;
    String[] expected = {
        "1,234.56", "$1,234.56", "123,456%", "1.23456E3"};
    for (int i = 0; i < 4; ++i) {
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(contents[i]));
        try {
            NumberFormat format = (NumberFormat) ois.readObject();
            String result = format.format(data);
            if (result.equals(expected[i])) {
                logln("OK: Deserialized bogus NumberFormat(new version read old version)");
            } else {
                errln("FAIL: the test data formats are not euqal");
            }
        } catch (Exception e) {
            warnln("FAIL: " + e.getMessage());
        }
    }
}
 
Example 5
Source File: NumberFormatRegressionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
void checkNBSPPatternRtNum(String testcase, NumberFormat nf, double myNumber) {
    String myString = nf.format(myNumber);
    
        double aNumber;
        try {
            aNumber = nf.parse(myString).doubleValue();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            errln("FAIL: " + testcase +" - failed to parse. " + e.toString());
            return;
        }
        if(Math.abs(aNumber-myNumber)>.001) {
        errln("FAIL: "+testcase+": formatted "+myNumber+", parsed into "+aNumber+"\n");
    } else {
        logln("PASS: "+testcase+": formatted "+myNumber+", parsed into "+aNumber+"\n");
    }
}
 
Example 6
Source File: NumberFormatRegressionTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
@Test
public void TestT9293() {
    NumberFormat fmt = NumberFormat.getCurrencyInstance();
    fmt.setParseStrict(true);

    final int val = 123456;
    String txt = fmt.format(123456);

    ParsePosition pos = new ParsePosition(0);
    Number num = fmt.parse(txt, pos);

    if (pos.getErrorIndex() >= 0) {
        errln("FAIL: Parsing " + txt + " - error index: " + pos.getErrorIndex());
    } else if (val != num.intValue()) {
        errln("FAIL: Parsed result: " + num + " - expected: " + val);
    }
}
 
Example 7
Source File: NumberRegressionTests.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * DecimalFormat does not round up correctly.
 */
@Test
public void Test4071492 (){
    double x = 0.00159999;
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(4);
    String out = nf.format(x);
    logln("0.00159999 formats with 4 fractional digits to " + out);
    String expected = "0.0016";
    if (!out.equals(expected))
        errln("FAIL: Expected " + expected);
}
 
Example 8
Source File: NumberRegressionTests.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * NumberFormat truncates data
 */
@Test
public void Test4167494() throws Exception {
    NumberFormat fmt = NumberFormat.getInstance(Locale.US);
    
    double a = Double.MAX_VALUE;
    String s = fmt.format(a);
    double b = fmt.parse(s).doubleValue();
    boolean match = a == b;
    if (match) {
        logln("" + a + " -> \"" + s + "\" -> " + b + " ok");
    } else {
        errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL");
    }

    // We don't test Double.MIN_VALUE because the locale data for the US
    // currently doesn't specify enough digits to display Double.MIN_VALUE.
    // This is correct for now; however, we leave this here as a reminder
    // in case we want to address this later.
    if (false) {
        a = Double.MIN_VALUE;
        s = fmt.format(a);
        b = fmt.parse(s).doubleValue();
        match = a == b;
        if (match) {
            logln("" + a + " -> \"" + s + "\" -> " + b + " ok");
        } else {
            errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL");
        }
    }
}
 
Example 9
Source File: NumberRegressionTests.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * A space as a group separator for localized pattern causes
 * wrong format.  WorkAround : use non-breaking space.
 */
@Test
public void Test4086575() {

    NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE);
    logln("nf toPattern1: " + ((DecimalFormat)nf).toPattern());
    logln("nf toLocPattern1: " + ((DecimalFormat)nf).toLocalizedPattern());

    // No group separator
    logln("...applyLocalizedPattern ###,00;(###,00) ");
    ((DecimalFormat)nf).applyLocalizedPattern("###,00;(###,00)");
    logln("nf toPattern2: " + ((DecimalFormat)nf).toPattern());
    logln("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern());

    logln("nf: " + nf.format(1234)); // 1234,00
    logln("nf: " + nf.format(-1234)); // (1234,00)

    // Space as group separator

    logln("...applyLocalizedPattern # ###,00;(# ###,00) ");
    ((DecimalFormat)nf).applyLocalizedPattern("#\u00a0###,00;(#\u00a0###,00)");
    logln("nf toPattern2: " + ((DecimalFormat)nf).toPattern());
    logln("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern());
    String buffer = nf.format(1234);
    if (!buffer.equals("1\u00a0234,00"))
        errln("nf : " + buffer); // Expect 1 234,00
    buffer = nf.format(-1234);
    if (!buffer.equals("(1\u00a0234,00)"))
        errln("nf : " + buffer); // Expect (1 234,00)

    // Erroneously prints:
    // 1234,00 ,
    // (1234,00 ,)

}
 
Example 10
Source File: ElapsedTimer.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private static String diffTime(NumberFormat fmt, long start, long end) {
    if(fmt==null) {
        fmt = getFormat();
    }
    synchronized(fmt) {
        long age = end - start;
        long diff = age/1000; // millis per second. Workaround ticket:7936 by using whole number seconds.
        return fmt.format(diff);
    }
}
 
Example 11
Source File: RbnfTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
void doTest(RuleBasedNumberFormat formatter, String[][] testData,
            boolean testParsing) {
    //        NumberFormat decFmt = NumberFormat.getInstance(Locale.US);
    NumberFormat decFmt = new DecimalFormat("#,###.################");
    try {
        for (int i = 0; i < testData.length; i++) {
            String number = testData[i][0];
            String expectedWords = testData[i][1];
            if (isVerbose()) {
                logln("test[" + i + "] number: " + number + " target: " + expectedWords);
            }
            Number num = decFmt.parse(number);
            String actualWords = formatter.format(num);

            if (!actualWords.equals(expectedWords)) {
                errln("Spot check format failed: for " + number + ", expected\n    "
                        + expectedWords + ", but got\n    " +
                        actualWords);
            }
            else if (testParsing) {
                String actualNumber = decFmt.format(formatter
                        .parse(actualWords));

                if (!actualNumber.equals(number)) {
                    errln("Spot check parse failed: for " + actualWords +
                            ", expected " + number + ", but got " +
                            actualNumber);
                }
            }
        }
    }
    catch (Throwable e) {
        e.printStackTrace();
        errln("Test failed with exception: " + e.toString());
    }
}
 
Example 12
Source File: NumberFormatRegressionTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * alphaWorks upgrade
 */
@Test
public void Test4161100() {
    NumberFormat nf = NumberFormat.getInstance(Locale.US);
    nf.setMinimumFractionDigits(1);
    nf.setMaximumFractionDigits(1);
    double a = -0.09;
    String s = nf.format(a);
    logln(a + " x " +
          ((DecimalFormat) nf).toPattern() + " = " + s);
    if (!s.equals("-0.1")) {
        errln("FAIL");
    }
}
 
Example 13
Source File: NumberRegressionTests.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * 4233840: NumberFormat does not round correctly
 */
@Test
public void test4233840() {
    float f = 0.0099f;

    NumberFormat nf = new DecimalFormat("0.##", new DecimalFormatSymbols(Locale.US));
nf.setMinimumFractionDigits(2);

String result = nf.format(f);

if (!result.equals("0.01")) {
    errln("FAIL: input: " + f + ", expected: 0.01, got: " + result);
}
}
 
Example 14
Source File: BigNumberFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void Test4161100() {
    NumberFormat f = NumberFormat.getInstance();
    f.setMinimumFractionDigits(1);
    f.setMaximumFractionDigits(1);
    double a = -0.09;
    String s = f.format(a);
    logln(a + " x " +
          ((DecimalFormat) f).toPattern() + " = " +
          s);
    if (!s.equals("-0.1")) {
        errln("FAIL");
    }
}
 
Example 15
Source File: BigNumberFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private void expect(NumberFormat fmt, Number n, String exp) {
    String saw = fmt.format(n);
    String pat = ((DecimalFormat) fmt).toPattern();
    if (saw.equals(exp)) {
        logln("Ok   " + showNumber(n) + " x " +
              pat + " = " +
              Utility.escape(saw));
    } else {
        errln("FAIL " + showNumber(n) + " x " +
              pat + " = \"" +
              Utility.escape(saw) + ", expected " + Utility.escape(exp));
    }
}
 
Example 16
Source File: NumberRegressionTests.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Number format data rounding errors for locale FR
 */
@Test
public void Test4070798 () {
    NumberFormat formatter;
    String tempString;
    /* User error :
    String expectedDefault = "-5\u00a0789,987";
    String expectedCurrency = "5\u00a0789,98\u00a0F";
    String expectedPercent = "-578\u00a0998%";
    */
    String expectedDefault = "-5\u00a0789,988";
    String expectedCurrency = "5\u00a0789,99\u00a0" + EURO; // euro
    String expectedPercent = "-578\u00a0999\u00a0%";

    formatter = NumberFormat.getNumberInstance(Locale.FRANCE);
    tempString = formatter.format (-5789.9876);

    if (tempString.equals(expectedDefault)) {
        logln ("Bug 4070798 default test passed.");
    } else {
        errln("Failed:" +
        " Expected " + expectedDefault +
        " Received " + tempString );
    }


    formatter = NumberFormat.getCurrencyInstance(Locale.FRANCE);
    tempString = formatter.format( 5789.9876 );

    if (tempString.equals(expectedCurrency) ) {
        logln ("Bug 4070798 currency test assed.");
    } else {
        errln("Failed:" +
        " Expected " + expectedCurrency +
        " Received " + tempString );
    }


    formatter = NumberFormat.getPercentInstance(Locale.FRANCE);
    tempString = formatter.format (-5789.9876);

    if (tempString.equals(expectedPercent) ) {
        logln ("Bug 4070798 percentage test passed.");
    } else {
        errln("Failed:" +
        " Expected " + expectedPercent +
        " Received " + tempString );
    }
}
 
Example 17
Source File: NumberRegressionTests.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Data rounding errors for French (Canada) locale
 */
@Test
public void Test4071005 () {

    NumberFormat formatter;
    String tempString;
/* user error :
    String expectedDefault = "-5 789,987";
    String expectedCurrency = "5 789,98\u00a0$";
    String expectedPercent = "-578 998%";
*/
    String expectedDefault = "-5\u00a0789,988";
    String expectedCurrency = "5\u00a0789,99\u00a0$";
    String expectedPercent = "-578\u00a0999\u00A0%";

    formatter = NumberFormat.getNumberInstance(Locale.CANADA_FRENCH);
    tempString = formatter.format (-5789.9876);
    if (tempString.equals(expectedDefault)) {
        logln ("Bug 4071005 default test passed.");
    } else {
        errln("Failed:" +
        " Expected " + expectedDefault +
        " Received " + tempString );
    }

    formatter = NumberFormat.getCurrencyInstance(Locale.CANADA_FRENCH);
    tempString = formatter.format( 5789.9876 ) ;

    if (tempString.equals(expectedCurrency) ) {
        logln ("Bug 4071005 currency test passed.");
    } else {
        errln("Failed:" +
        " Expected " + expectedCurrency +
        " Received " + tempString );
    }
    formatter = NumberFormat.getPercentInstance(Locale.CANADA_FRENCH);
    tempString = formatter.format (-5789.9876);

    if (tempString.equals(expectedPercent) ) {
        logln ("Bug 4071005 percentage test passed.");
    } else {
        errln("Failed:" +
        " Expected " + expectedPercent +
        " Received " + tempString );
    }
}
 
Example 18
Source File: NumberRegressionTests.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Data rounding errors for German (Germany) locale
 */
@Test
public void Test4071014 () {
    NumberFormat formatter;
    String tempString;
    /* user error :
    String expectedDefault = "-5.789,987";
    String expectedCurrency = "5.789,98\u00a0DM";
    String expectedPercent = "-578.998%";
    */
    String expectedDefault = "-5.789,988";
    String expectedCurrency = "5.789,99\u00a0" + EURO;
    String expectedPercent = "-578.999\u00a0%";

    formatter = NumberFormat.getNumberInstance(Locale.GERMANY);
    tempString = formatter.format (-5789.9876);

    if (tempString.equals(expectedDefault)) {
        logln ("Bug 4071014 default test passed.");
    } else {
        errln("Failed:" +
        " Expected " + expectedDefault +
        " Received " + tempString );
    }

    formatter = NumberFormat.getCurrencyInstance(Locale.GERMANY);
    tempString = formatter.format( 5789.9876 ) ;

    if (tempString.equals(expectedCurrency) ) {
        logln ("Bug 4071014 currency test passed.");
    } else {
        errln("Failed:" +
        " Expected " + expectedCurrency +
        " Received " + tempString );
    }

    formatter = NumberFormat.getPercentInstance(Locale.GERMANY);
    tempString = formatter.format (-5789.9876);

    if (tempString.equals(expectedPercent) ) {
        logln ("Bug 4071014 percentage test passed.");
    } else {
        errln("Failed:" +
        " Expected " + expectedPercent +
        " Received " + tempString );
    }

}
 
Example 19
Source File: NumberRegressionTests.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Data rounding errors for Italian locale number formats
 * Note- with the Euro, there is no need for currency rounding anymore
 */
@Test
public void Test4071859 () {
    NumberFormat formatter;
    String tempString;
    /* user error :
    String expectedDefault = "-5.789,987";
    String expectedCurrency = "-L.\u00a05.789,98";
    String expectedPercent = "-578.998%";
    */
    String expectedDefault = "-5.789,988";
    String expectedCurrency = "-5.789,99\u00A0" + EURO;
    String expectedPercent = "-578.999%";

    formatter = NumberFormat.getNumberInstance(Locale.ITALY);
    tempString = formatter.format (-5789.9876);

    if (tempString.equals(expectedDefault)) {
        logln ("Bug 4071859 default test passed.");
    } else {
        errln("a) Failed:" +
        " Expected " + expectedDefault +
        " Received " + tempString );
    }

    formatter = NumberFormat.getCurrencyInstance(Locale.ITALY);
    tempString = formatter.format( -5789.9876 ) ;

    if (tempString.equals(expectedCurrency) ) {
        logln ("Bug 4071859 currency test passed.");
    } else {
        errln("b) Failed:" +
        " Expected " + expectedCurrency +
        " Received " + tempString );
    }

    formatter = NumberFormat.getPercentInstance(Locale.ITALY);
    tempString = formatter.format (-5789.9876);

    if (tempString.equals(expectedPercent) ) {
        logln ("Bug 4071859 percentage test passed.");
    } else {
        errln("c) Failed:" +
        " Expected " + expectedPercent +
        " Received " + tempString );
    }

}
 
Example 20
Source File: NumberFormatRoundTripTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
private void _test(NumberFormat fmt, Number value) {
    logln("test data = " + value);
    fmt.setMaximumFractionDigits(999);
    String s, s2;
    if (value.getClass().getName().equalsIgnoreCase("java.lang.Double"))
        s = fmt.format(value.doubleValue());
    else
        s = fmt.format(value.longValue());

    Number n = new Double(0);
    boolean show = verbose;
    if (DEBUG)
        logln(
        /*value.getString(temp) +*/ " F> " + s);
    try {
        n = fmt.parse(s);
    } catch (java.text.ParseException e) {
        System.out.println(e);
    }

    if (DEBUG)
        logln(s + " P> " /*+ n.getString(temp)*/);

    if (value.getClass().getName().equalsIgnoreCase("java.lang.Double"))
        s2 = fmt.format(n.doubleValue());
    else
        s2 = fmt.format(n.longValue());

    if (DEBUG)
        logln(/*n.getString(temp) +*/ " F> " + s2);

    if (STRING_COMPARE) {
        if (!s.equals(s2)) {
            errln("*** STRING ERROR \"" + s + "\" != \"" + s2 + "\"");
            show = true;
        }
    }

    if (EXACT_NUMERIC_COMPARE) {
        if (value != n) {
            errln("*** NUMERIC ERROR");
            show = true;
        }
    } else {
        // Compute proportional error
        double error = proportionalError(value, n);

        if (error > MAX_ERROR) {
            errln("*** NUMERIC ERROR " + error);
            show = true;
        }

        if (error > max_numeric_error)
            max_numeric_error = error;
        if (error < min_numeric_error)
            min_numeric_error = error;
    }

    if (show)
        logln(
        /*value.getString(temp) +*/ value.getClass().getName() + " F> " + s + " P> " +
        /*n.getString(temp) +*/ n.getClass().getName() + " F> " + s2);

}