2 /*****************************************************************************************
\r
4 * Copyright (C) 1996-2009, International Business Machines
\r
5 * Corporation and others. All Rights Reserved.
\r
9 * Port From: JDK 1.4b1 : java.text.Format.NumberRegression
\r
10 * Source File: java/text/format/NumberRegression.java
\r
14 * @test 1.49 01/05/21
\r
15 * @bug 4052223 4059870 4061302 4062486 4066646 4068693 4070798 4071005 4071014
\r
16 * 4071492 4071859 4074454 4074620 4075713 4083018 4086575 4087244 4087245
\r
17 * 4087251 4087535 4088161 4088503 4090489 4090504 4092480 4092561 4095713
\r
18 * 4098741 4099404 4101481 4106658 4106662 4106664 4108738 4110936 4122840
\r
19 * 4125885 4134034 4134300 4140009 4141750 4145457 4147295 4147706 4162198
\r
20 * 4162852 4167494 4170798 4176114 4179818 4185761 4212072 4212073 4216742
\r
21 * 4217661 4243011 4243108 4330377 4233840
\r
22 * @summary Regression tests for NumberFormat and associated classes
\r
25 package com.ibm.icu.dev.test.format;
\r
27 //import com.ibm.icu.impl.ICULocaleData;
\r
28 import com.ibm.icu.impl.ICUResourceBundle;
\r
29 import com.ibm.icu.text.*;
\r
30 import com.ibm.icu.util.*;
\r
33 import java.math.BigInteger;
\r
34 import java.text.FieldPosition;
\r
35 import java.text.ParseException;
\r
36 import java.text.ParsePosition;
\r
37 import java.util.Date;
\r
38 import java.util.Locale;
\r
40 public class NumberRegression extends com.ibm.icu.dev.test.TestFmwk {
\r
42 public static void main(String[] args) throws Exception {
\r
43 new NumberRegression().run(args);
\r
46 private static final char EURO = '\u20ac';
\r
49 * NumberFormat.equals comparing with null should always return false.
\r
51 public void Test4075713(){
\r
54 MyNumberFormatTest tmp = new MyNumberFormatTest();
\r
55 if (!tmp.equals(null))
\r
56 logln("NumberFormat.equals passed");
\r
57 } catch (NullPointerException e) {
\r
58 errln("(new MyNumberFormatTest()).equals(null) throws unexpected exception");
\r
63 * NumberFormat.equals comparing two obj equal even the setGroupingUsed
\r
64 * flag is different.
\r
66 public void Test4074620() {
\r
68 MyNumberFormatTest nf1 = new MyNumberFormatTest();
\r
69 MyNumberFormatTest nf2 = new MyNumberFormatTest();
\r
71 nf1.setGroupingUsed(false);
\r
72 nf2.setGroupingUsed(true);
\r
74 if (nf1.equals(nf2)) errln("Test for bug 4074620 failed");
\r
75 else logln("Test for bug 4074620 passed.");
\r
81 * DecimalFormat.format() incorrectly uses maxFractionDigits setting.
\r
84 public void Test4088161 (){
\r
85 DecimalFormat df = new DecimalFormat();
\r
87 df.setMinimumFractionDigits(0);
\r
88 df.setMaximumFractionDigits(16);
\r
89 StringBuffer sBuf1 = new StringBuffer("");
\r
90 FieldPosition fp1 = new FieldPosition(0);
\r
92 logln("maxFractionDigits = " + df.getMaximumFractionDigits());
\r
93 logln(" format(d) = '" + df.format(d, sBuf1, fp1) + "'");
\r
94 df.setMaximumFractionDigits(17);
\r
95 StringBuffer sBuf2 = new StringBuffer("");
\r
96 FieldPosition fp2 = new FieldPosition(0);
\r
97 logln("maxFractionDigits = " + df.getMaximumFractionDigits());
\r
98 df.format(d, sBuf2, fp2);
\r
99 if (!sBuf2.toString().equals("100"))
\r
100 errln(" format(d) = '" + sBuf2 + "'");
\r
103 * DecimalFormatSymbols should be cloned in the ctor DecimalFormat.
\r
104 * DecimalFormat(String, DecimalFormatSymbols).
\r
106 public void Test4087245 (){
\r
107 DecimalFormatSymbols symbols = new DecimalFormatSymbols();
\r
108 DecimalFormat df = new DecimalFormat("#,##0.0", symbols);
\r
110 StringBuffer buf1 = new StringBuffer();
\r
111 StringBuffer buf2 = new StringBuffer();
\r
112 logln("format(" + n + ") = " +
\r
113 df.format(n, buf1, new FieldPosition(0)));
\r
114 symbols.setDecimalSeparator('p'); // change value of field
\r
115 logln("format(" + n + ") = " +
\r
116 df.format(n, buf2, new FieldPosition(0)));
\r
117 if (!buf1.toString().equals(buf2.toString()))
\r
118 errln("Test for bug 4087245 failed");
\r
121 * DecimalFormat.format() incorrectly formats 0.0
\r
123 public void Test4087535 ()
\r
125 DecimalFormat df = new DecimalFormat();
\r
126 df.setMinimumIntegerDigits(0);
\r
129 String buffer = new String();
\r
130 buffer = df.format(n);
\r
131 if (buffer.length() == 0)
\r
132 errln(n + ": '" + buffer + "'");
\r
134 buffer = df.format(n);
\r
135 if (buffer.length() == 0)
\r
136 errln(n + ": '" + buffer + "'");
\r
140 * DecimalFormat.format fails when groupingSize is set to 0.
\r
142 public void Test4088503 (){
\r
143 DecimalFormat df = new DecimalFormat();
\r
144 df.setGroupingSize(0);
\r
145 StringBuffer sBuf = new StringBuffer("");
\r
146 FieldPosition fp = new FieldPosition(0);
\r
148 logln(df.format(123, sBuf, fp).toString());
\r
149 } catch (Exception foo) {
\r
150 errln("Test for bug 4088503 failed.");
\r
155 * NumberFormat.getCurrencyInstance is wrong.
\r
157 public void Test4066646 () {
\r
158 //float returnfloat = 0.0f; //The variable is never used
\r
159 assignFloatValue(2.04f);
\r
160 assignFloatValue(2.03f);
\r
161 assignFloatValue(2.02f);
\r
162 assignFloatValue(0.0f);
\r
165 public float assignFloatValue(float returnfloat)
\r
167 logln(" VALUE " + returnfloat);
\r
168 NumberFormat nfcommon = NumberFormat.getCurrencyInstance(Locale.US);
\r
169 nfcommon.setGroupingUsed(false);
\r
171 String stringValue = nfcommon.format(returnfloat).substring(1);
\r
172 if (Float.valueOf(stringValue).floatValue() != returnfloat)
\r
173 errln(" DISPLAYVALUE " + stringValue);
\r
174 return returnfloat;
\r
175 } // End Of assignFloatValue()
\r
178 * DecimalFormat throws exception when parsing "0"
\r
180 public void Test4059870() {
\r
181 DecimalFormat format = new DecimalFormat("00");
\r
183 logln(format.parse("0").toString());
\r
184 } catch (Exception e) { errln("Test for bug 4059870 failed : " + e); }
\r
187 * DecimalFormatSymbol.equals should always return false when
\r
188 * comparing with null.
\r
191 public void Test4083018 (){
\r
192 DecimalFormatSymbols dfs = new DecimalFormatSymbols();
\r
194 if (!dfs.equals(null))
\r
195 logln("Test Passed!");
\r
196 } catch (Exception foo) {
\r
197 errln("Test for bug 4083018 failed => Message : " + foo.getMessage());
\r
201 * DecimalFormat does not round up correctly.
\r
203 public void Test4071492 (){
\r
204 double x = 0.00159999;
\r
205 NumberFormat nf = NumberFormat.getInstance();
\r
206 nf.setMaximumFractionDigits(4);
\r
207 String out = nf.format(x);
\r
208 logln("0.00159999 formats with 4 fractional digits to " + out);
\r
209 String expected = "0.0016";
\r
210 if (!out.equals(expected))
\r
211 errln("FAIL: Expected " + expected);
\r
215 * A space as a group separator for localized pattern causes
\r
216 * wrong format. WorkAround : use non-breaking space.
\r
218 public void Test4086575() {
\r
220 NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE);
\r
221 logln("nf toPattern1: " + ((DecimalFormat)nf).toPattern());
\r
222 logln("nf toLocPattern1: " + ((DecimalFormat)nf).toLocalizedPattern());
\r
224 // No group separator
\r
225 logln("...applyLocalizedPattern ###,00;(###,00) ");
\r
226 ((DecimalFormat)nf).applyLocalizedPattern("###,00;(###,00)");
\r
227 logln("nf toPattern2: " + ((DecimalFormat)nf).toPattern());
\r
228 logln("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern());
\r
230 logln("nf: " + nf.format(1234)); // 1234,00
\r
231 logln("nf: " + nf.format(-1234)); // (1234,00)
\r
233 // Space as group separator
\r
235 logln("...applyLocalizedPattern # ###,00;(# ###,00) ");
\r
236 ((DecimalFormat)nf).applyLocalizedPattern("#\u00a0###,00;(#\u00a0###,00)");
\r
237 logln("nf toPattern2: " + ((DecimalFormat)nf).toPattern());
\r
238 logln("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern());
\r
239 String buffer = nf.format(1234);
\r
240 if (!buffer.equals("1\u00a0234,00"))
\r
241 errln("nf : " + buffer); // Expect 1 234,00
\r
242 buffer = nf.format(-1234);
\r
243 if (!buffer.equals("(1\u00a0234,00)"))
\r
244 errln("nf : " + buffer); // Expect (1 234,00)
\r
246 // Erroneously prints:
\r
252 * DecimalFormat.parse returns wrong value
\r
254 public void Test4068693()
\r
256 logln("----- Test Application -----");
\r
257 //ParsePosition pos;
\r
258 DecimalFormat df = new DecimalFormat();
\r
259 Number d = df.parse("123.55456", new ParsePosition(0));
\r
260 if (!d.toString().equals("123.55456")) {
\r
261 errln("Result -> " + d.doubleValue());
\r
265 /* bugs 4069754, 4067878
\r
266 * null pointer thrown when accessing a deserialized DecimalFormat
\r
269 public void Test4069754() throws Exception
\r
272 ByteArrayOutputStream baos = new ByteArrayOutputStream();
\r
273 ObjectOutputStream oos = new ObjectOutputStream(baos);
\r
274 myformat it = new myformat();
\r
276 oos.writeObject(it);
\r
280 byte [] bytes = baos.toByteArray();
\r
281 ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
\r
282 myformat o = (myformat)ois.readObject();
\r
286 if (!o._dateFormat.equals(it._dateFormat)) {
\r
287 throw new Exception("The saved and loaded object are not equals!");
\r
289 logln("Compare OK!");
\r
290 //} catch (Exception foo) {
\r
291 //errln("Test for bug 4069754 or 4057878 failed => Exception: " + foo.getMessage());
\r
296 * DecimalFormat.applyPattern(String) allows illegal patterns
\r
298 public void Test4087251 (){
\r
299 DecimalFormat df = new DecimalFormat();
\r
301 df.applyPattern("#.#.#");
\r
302 logln("toPattern() returns \"" + df.toPattern() + "\"");
\r
303 errln("applyPattern(\"#.#.#\") doesn't throw IllegalArgumentException");
\r
304 } catch (IllegalArgumentException e) {
\r
305 logln("Caught Illegal Argument Error !");
\r
307 // Second test; added 5/11/98 when reported to fail on 1.2b3
\r
309 df.applyPattern("#0.0#0#0");
\r
310 logln("toPattern() returns \"" + df.toPattern() + "\"");
\r
311 errln("applyPattern(\"#0.0#0#0\") doesn't throw IllegalArgumentException");
\r
312 } catch (IllegalArgumentException e) {
\r
313 logln("Ok - IllegalArgumentException for #0.0#0#0");
\r
318 * DecimalFormat.format() loses precision
\r
320 public void Test4090489 (){
\r
321 DecimalFormat df = new DecimalFormat();
\r
322 df.setMinimumFractionDigits(10);
\r
323 df.setGroupingUsed(false);
\r
324 double d = 1.000000000000001E7;
\r
325 java.math.BigDecimal bd = new java.math.BigDecimal(d);
\r
326 StringBuffer sb = new StringBuffer("");
\r
327 FieldPosition fp = new FieldPosition(0);
\r
329 logln("BigDecimal.toString(): " + bd.toString());
\r
330 df.format(d, sb, fp);
\r
331 if (!sb.toString().equals("10000000.0000000100")) {
\r
332 errln("DecimalFormat.format(): " + sb.toString());
\r
337 * DecimalFormat.format() loses precision
\r
339 public void Test4090504 ()
\r
343 DecimalFormat df = new DecimalFormat();
\r
347 for (int i = 17; i <= 20; i++) {
\r
348 df.setMaximumFractionDigits(i);
\r
349 sb = new StringBuffer("");
\r
350 fp = new FieldPosition(0);
\r
351 logln(" getMaximumFractionDigits() = " + i);
\r
352 logln(" formated: " + df.format(d, sb, fp));
\r
354 } catch (Exception foo) {
\r
355 errln("Bug 4090504 regression test failed. Message : " + foo.getMessage());
\r
359 * DecimalFormat.parse(String str, ParsePosition pp) loses precision
\r
361 public void Test4095713 ()
\r
363 DecimalFormat df = new DecimalFormat();
\r
364 String str = "0.1234";
\r
365 Double d1 = new Double(str);
\r
366 Number d2 = df.parse(str, new ParsePosition(0));
\r
367 logln(d1.toString());
\r
368 if (d2.doubleValue() != d1.doubleValue())
\r
369 errln("Bug 4095713 test failed, new double value : " + d2.doubleValue());
\r
373 * DecimalFormat.parse() fails when multiplier is not set to 1
\r
375 public void Test4092561 ()
\r
377 Locale savedLocale = Locale.getDefault();
\r
378 Locale.setDefault(Locale.US);
\r
379 DecimalFormat df = new DecimalFormat();
\r
380 String str = Long.toString(Long.MIN_VALUE);
\r
381 logln("Long.MIN_VALUE : " + df.parse(str, new ParsePosition(0)).toString());
\r
382 df.setMultiplier(100);
\r
383 Number num = df.parse(str, new ParsePosition(0));
\r
384 if (num.doubleValue() != -9.223372036854776E16) {
\r
385 errln("Bug 4092561 test failed when multiplier is set to not 1.");
\r
387 Locale.setDefault(savedLocale);
\r
391 * DecimalFormat: Negative format ignored.
\r
393 public void Test4092480 ()
\r
395 DecimalFormat dfFoo = new DecimalFormat("000");
\r
398 dfFoo.applyPattern("0000;-000");
\r
399 if (!dfFoo.toPattern().equals("#0000"))
\r
400 errln("dfFoo.toPattern : " + dfFoo.toPattern());
\r
401 logln(dfFoo.format(42));
\r
402 logln(dfFoo.format(-42));
\r
403 dfFoo.applyPattern("000;-000");
\r
404 if (!dfFoo.toPattern().equals("#000"))
\r
405 errln("dfFoo.toPattern : " + dfFoo.toPattern());
\r
406 logln(dfFoo.format(42));
\r
407 logln(dfFoo.format(-42));
\r
409 dfFoo.applyPattern("000;-0000");
\r
410 if (!dfFoo.toPattern().equals("#000"))
\r
411 errln("dfFoo.toPattern : " + dfFoo.toPattern());
\r
412 logln(dfFoo.format(42));
\r
413 logln(dfFoo.format(-42));
\r
415 dfFoo.applyPattern("0000;-000");
\r
416 if (!dfFoo.toPattern().equals("#0000"))
\r
417 errln("dfFoo.toPattern : " + dfFoo.toPattern());
\r
418 logln(dfFoo.format(42));
\r
419 logln(dfFoo.format(-42));
\r
420 } catch (Exception foo) {
\r
421 errln("Message " + foo.getMessage());
\r
425 * NumberFormat.getCurrencyInstance() produces format that uses
\r
426 * decimal separator instead of monetary decimal separator.
\r
428 * Rewrote this test not to depend on the actual pattern. Pattern should
\r
429 * never contain the monetary separator! Decimal separator in pattern is
\r
430 * interpreted as monetary separator if currency symbol is seen!
\r
432 public void Test4087244 () {
\r
433 Locale de = new Locale("pt", "PT");
\r
434 DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(de);
\r
435 DecimalFormatSymbols sym = df.getDecimalFormatSymbols();
\r
436 sym.setMonetaryDecimalSeparator('$');
\r
437 df.setDecimalFormatSymbols(sym);
\r
438 char decSep = sym.getDecimalSeparator();
\r
439 char monSep = sym.getMonetaryDecimalSeparator();
\r
440 //char zero = sym.getZeroDigit(); //The variable is never used
\r
441 if (decSep == monSep) {
\r
442 errln("ERROR in test: want decimal sep != monetary sep");
\r
444 df.setMinimumIntegerDigits(1);
\r
445 df.setMinimumFractionDigits(2);
\r
446 String str = df.format(1.23);
\r
447 String monStr = "1" + monSep + "23";
\r
448 String decStr = "1" + decSep + "23";
\r
449 if (str.indexOf(monStr) >= 0 && str.indexOf(decStr) < 0) {
\r
450 logln("OK: 1.23 -> \"" + str + "\" contains \"" +
\r
451 monStr + "\" and not \"" + decStr + '"');
\r
453 errln("FAIL: 1.23 -> \"" + str + "\", should contain \"" +
\r
455 "\" and not \"" + decStr + '"');
\r
460 * Number format data rounding errors for locale FR
\r
462 public void Test4070798 () {
\r
463 NumberFormat formatter;
\r
466 String expectedDefault = "-5\u00a0789,987";
\r
467 String expectedCurrency = "5\u00a0789,98\u00a0F";
\r
468 String expectedPercent = "-578\u00a0998%";
\r
470 String expectedDefault = "-5\u00a0789,988";
\r
471 String expectedCurrency = "5\u00a0789,99\u00a0" + EURO; // euro
\r
472 String expectedPercent = "-578\u00a0999\u00a0%";
\r
474 formatter = NumberFormat.getNumberInstance(Locale.FRANCE);
\r
475 tempString = formatter.format (-5789.9876);
\r
477 if (tempString.equals(expectedDefault)) {
\r
478 logln ("Bug 4070798 default test passed.");
\r
481 " Expected " + expectedDefault +
\r
482 " Received " + tempString );
\r
486 formatter = NumberFormat.getCurrencyInstance(Locale.FRANCE);
\r
487 tempString = formatter.format( 5789.9876 );
\r
489 if (tempString.equals(expectedCurrency) ) {
\r
490 logln ("Bug 4070798 currency test assed.");
\r
493 " Expected " + expectedCurrency +
\r
494 " Received " + tempString );
\r
498 formatter = NumberFormat.getPercentInstance(Locale.FRANCE);
\r
499 tempString = formatter.format (-5789.9876);
\r
501 if (tempString.equals(expectedPercent) ) {
\r
502 logln ("Bug 4070798 percentage test passed.");
\r
505 " Expected " + expectedPercent +
\r
506 " Received " + tempString );
\r
510 * Data rounding errors for French (Canada) locale
\r
512 public void Test4071005 () {
\r
514 NumberFormat formatter;
\r
517 String expectedDefault = "-5 789,987";
\r
518 String expectedCurrency = "5 789,98\u00a0$";
\r
519 String expectedPercent = "-578 998%";
\r
521 String expectedDefault = "-5\u00a0789,988";
\r
522 String expectedCurrency = "5\u00a0789,99\u00a0$";
\r
523 String expectedPercent = "-578\u00a0999\u00A0%";
\r
525 formatter = NumberFormat.getNumberInstance(Locale.CANADA_FRENCH);
\r
526 tempString = formatter.format (-5789.9876);
\r
527 if (tempString.equals(expectedDefault)) {
\r
528 logln ("Bug 4071005 default test passed.");
\r
531 " Expected " + expectedDefault +
\r
532 " Received " + tempString );
\r
535 formatter = NumberFormat.getCurrencyInstance(Locale.CANADA_FRENCH);
\r
536 tempString = formatter.format( 5789.9876 ) ;
\r
538 if (tempString.equals(expectedCurrency) ) {
\r
539 logln ("Bug 4071005 currency test passed.");
\r
542 " Expected " + expectedCurrency +
\r
543 " Received " + tempString );
\r
545 formatter = NumberFormat.getPercentInstance(Locale.CANADA_FRENCH);
\r
546 tempString = formatter.format (-5789.9876);
\r
548 if (tempString.equals(expectedPercent) ) {
\r
549 logln ("Bug 4071005 percentage test passed.");
\r
552 " Expected " + expectedPercent +
\r
553 " Received " + tempString );
\r
558 * Data rounding errors for German (Germany) locale
\r
560 public void Test4071014 () {
\r
561 NumberFormat formatter;
\r
564 String expectedDefault = "-5.789,987";
\r
565 String expectedCurrency = "5.789,98\u00a0DM";
\r
566 String expectedPercent = "-578.998%";
\r
568 String expectedDefault = "-5.789,988";
\r
569 String expectedCurrency = "5.789,99\u00a0" + EURO;
\r
570 String expectedPercent = "-578.999\u00a0%";
\r
572 formatter = NumberFormat.getNumberInstance(Locale.GERMANY);
\r
573 tempString = formatter.format (-5789.9876);
\r
575 if (tempString.equals(expectedDefault)) {
\r
576 logln ("Bug 4071014 default test passed.");
\r
579 " Expected " + expectedDefault +
\r
580 " Received " + tempString );
\r
583 formatter = NumberFormat.getCurrencyInstance(Locale.GERMANY);
\r
584 tempString = formatter.format( 5789.9876 ) ;
\r
586 if (tempString.equals(expectedCurrency) ) {
\r
587 logln ("Bug 4071014 currency test passed.");
\r
590 " Expected " + expectedCurrency +
\r
591 " Received " + tempString );
\r
594 formatter = NumberFormat.getPercentInstance(Locale.GERMANY);
\r
595 tempString = formatter.format (-5789.9876);
\r
597 if (tempString.equals(expectedPercent) ) {
\r
598 logln ("Bug 4071014 percentage test passed.");
\r
601 " Expected " + expectedPercent +
\r
602 " Received " + tempString );
\r
607 * Data rounding errors for Italian locale number formats
\r
608 * Note- with the Euro, there is no need for currency rounding anymore
\r
610 public void Test4071859 () {
\r
611 NumberFormat formatter;
\r
614 String expectedDefault = "-5.789,987";
\r
615 String expectedCurrency = "-L.\u00a05.789,98";
\r
616 String expectedPercent = "-578.998%";
\r
618 String expectedDefault = "-5.789,988";
\r
619 String expectedCurrency = "-" + EURO + "\u00a05.789,99";
\r
620 String expectedPercent = "-578.999%";
\r
622 formatter = NumberFormat.getNumberInstance(Locale.ITALY);
\r
623 tempString = formatter.format (-5789.9876);
\r
625 if (tempString.equals(expectedDefault)) {
\r
626 logln ("Bug 4071859 default test passed.");
\r
628 errln("a) Failed:" +
\r
629 " Expected " + expectedDefault +
\r
630 " Received " + tempString );
\r
633 formatter = NumberFormat.getCurrencyInstance(Locale.ITALY);
\r
634 tempString = formatter.format( -5789.9876 ) ;
\r
636 if (tempString.equals(expectedCurrency) ) {
\r
637 logln ("Bug 4071859 currency test passed.");
\r
639 errln("b) Failed:" +
\r
640 " Expected " + expectedCurrency +
\r
641 " Received " + tempString );
\r
644 formatter = NumberFormat.getPercentInstance(Locale.ITALY);
\r
645 tempString = formatter.format (-5789.9876);
\r
647 if (tempString.equals(expectedPercent) ) {
\r
648 logln ("Bug 4071859 percentage test passed.");
\r
650 errln("c) Failed:" +
\r
651 " Expected " + expectedPercent +
\r
652 " Received " + tempString );
\r
657 * Test rounding for nearest even.
\r
659 public void Test4093610()
\r
661 DecimalFormat df = new DecimalFormat("#0.#");
\r
662 roundingTest(df, 12.35, "12.4");
\r
663 roundingTest(df, 12.45, "12.4");
\r
664 roundingTest(df, 12.452,"12.5");
\r
665 roundingTest(df, 12.55, "12.6");
\r
666 roundingTest(df, 12.65, "12.6");
\r
667 roundingTest(df, 12.652,"12.7");
\r
668 roundingTest(df, 12.75, "12.8");
\r
669 roundingTest(df, 12.752,"12.8");
\r
670 roundingTest(df, 12.85, "12.8");
\r
671 roundingTest(df, 12.852,"12.9");
\r
672 roundingTest(df, 12.95, "13");
\r
673 roundingTest(df, 12.952,"13");
\r
676 void roundingTest(DecimalFormat df, double x, String expected)
\r
678 String out = df.format(x);
\r
679 logln("" + x + " formats with 1 fractional digits to " + out);
\r
680 if (!out.equals(expected)) errln("FAIL: Expected " + expected);
\r
683 * Tests the setMaximumFractionDigits limit.
\r
685 public void Test4098741()
\r
688 NumberFormat fmt = NumberFormat.getPercentInstance();
\r
689 fmt.setMaximumFractionDigits(20);
\r
690 logln(fmt.format(.001));
\r
691 } catch (Exception foo) {
\r
692 warnln("Bug 4098471 failed with exception thrown : " + foo.getMessage());
\r
696 * Tests illegal pattern exception.
\r
697 * Fix comment : HShih A31 Part1 will not be fixed and javadoc needs to be updated.
\r
698 * Part2 has been fixed.
\r
700 public void Test4074454()
\r
703 DecimalFormat fmt = new DecimalFormat("#,#00.00;-#.#");
\r
704 logln("format 3456.78: " + fmt.format(3456.78)); //fix "The variable 'fmt' is never used"
\r
705 logln("Inconsistent negative pattern is fine.");
\r
706 DecimalFormat newFmt = new DecimalFormat("#,#00.00 p''ieces;-#,#00.00 p''ieces");
\r
707 String tempString = newFmt.format(3456.78);
\r
708 if (!tempString.equals("3,456.78 p'ieces"))
\r
709 errln("Failed! 3456.78 p'ieces expected, but got : " + tempString);
\r
710 } catch (Exception foo) {
\r
711 warnln("An exception was thrown for any inconsistent negative pattern.");
\r
715 * Tests all different comments.
\r
716 * Response to some comments :
\r
717 * [1] DecimalFormat.parse API documentation is more than just one line.
\r
718 * This is not a reproducable doc error in 116 source code.
\r
719 * [2] See updated javadoc.
\r
721 * [4] NumberFormat.parse(String, ParsePosition) : If parsing fails,
\r
722 * a null object will be returned. The unchanged parse position also
\r
723 * reflects an error.
\r
724 * NumberFormat.parse(String) : If parsing fails, an ParseException
\r
726 * See updated javadoc for more details.
\r
727 * [5] See updated javadoc.
\r
728 * [6] See updated javadoc.
\r
729 * [7] This is a correct behavior if the DateFormat object is linient.
\r
730 * Otherwise, an IllegalArgumentException will be thrown when formatting
\r
731 * "January 35". See GregorianCalendar class javadoc for more details.
\r
733 public void Test4099404()
\r
736 DecimalFormat fmt = new DecimalFormat("000.0#0");
\r
737 logln("format 3456.78: " + fmt.format(3456.78)); //fix "The variable 'fmt' is never used"
\r
738 errln("Bug 4099404 failed applying illegal pattern \"000.0#0\"");
\r
739 } catch (Exception foo) {
\r
740 logln("Bug 4099404 pattern \"000.0#0\" passed");
\r
743 DecimalFormat fmt = new DecimalFormat("0#0.000");
\r
744 logln("format 3456.78: " + fmt.format(3456.78)); //fix "The variable 'fmt' is never used"
\r
745 errln("Bug 4099404 failed applying illegal pattern \"0#0.000\"");
\r
746 } catch (Exception foo) {
\r
747 logln("Bug 4099404 pattern \"0#0.000\" passed");
\r
751 * DecimalFormat.applyPattern doesn't set minimum integer digits
\r
753 public void Test4101481()
\r
755 DecimalFormat sdf = new DecimalFormat("#,##0");
\r
756 if (sdf.getMinimumIntegerDigits() != 1)
\r
757 errln("Minimum integer digits : " + sdf.getMinimumIntegerDigits());
\r
760 * Tests ParsePosition.setErrorPosition() and ParsePosition.getErrorPosition().
\r
762 public void Test4052223()
\r
765 DecimalFormat fmt = new DecimalFormat("#,#00.00");
\r
766 Number num = fmt.parse("abc3");
\r
767 errln("Bug 4052223 failed : can't parse string \"a\". Got " + num);
\r
768 } catch (ParseException foo) {
\r
769 logln("Caught expected ParseException : " + foo.getMessage() + " at index : " + foo.getErrorOffset());
\r
773 * API tests for API addition request A9.
\r
775 public void Test4061302()
\r
777 DecimalFormatSymbols fmt = new DecimalFormatSymbols();
\r
778 String currency = fmt.getCurrencySymbol();
\r
779 String intlCurrency = fmt.getInternationalCurrencySymbol();
\r
780 char monDecSeparator = fmt.getMonetaryDecimalSeparator();
\r
781 if (currency.equals("") ||
\r
782 intlCurrency.equals("") ||
\r
783 monDecSeparator == 0) {
\r
784 errln("getCurrencySymbols failed, got empty string.");
\r
786 logln("Before set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator);
\r
787 fmt.setCurrencySymbol("XYZ");
\r
788 fmt.setInternationalCurrencySymbol("ABC");
\r
789 fmt.setMonetaryDecimalSeparator('*');
\r
790 currency = fmt.getCurrencySymbol();
\r
791 intlCurrency = fmt.getInternationalCurrencySymbol();
\r
792 monDecSeparator = fmt.getMonetaryDecimalSeparator();
\r
793 if (!currency.equals("XYZ") ||
\r
794 !intlCurrency.equals("ABC") ||
\r
795 monDecSeparator != '*') {
\r
796 errln("setCurrencySymbols failed.");
\r
798 logln("After set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator);
\r
801 * API tests for API addition request A23. FieldPosition.getBeginIndex and
\r
802 * FieldPosition.getEndIndex.
\r
804 public void Test4062486()
\r
806 DecimalFormat fmt = new DecimalFormat("#,##0.00");
\r
807 StringBuffer formatted = new StringBuffer();
\r
808 FieldPosition field = new FieldPosition(0);
\r
809 Double num = new Double(1234.5);
\r
810 fmt.format(num, formatted, field);
\r
811 if (field.getBeginIndex() != 0 && field.getEndIndex() != 5)
\r
812 errln("Format 1234.5 failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex());
\r
813 field.setBeginIndex(7);
\r
814 field.setEndIndex(4);
\r
815 if (field.getBeginIndex() != 7 && field.getEndIndex() != 4)
\r
816 errln("Set begin/end field indexes failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex());
\r
820 * DecimalFormat.parse incorrectly works with a group separator.
\r
822 public void Test4108738()
\r
825 DecimalFormat df = new DecimalFormat("#,##0.###", new
\r
826 DecimalFormatSymbols(java.util.Locale.US));
\r
827 String text = "1.222,111";
\r
828 Number num = df.parse(text,new ParsePosition(0));
\r
829 if (!num.toString().equals("1.222"))
\r
830 errln("\"" + text + "\" is parsed as " + num);
\r
831 text = "1.222x111";
\r
832 num = df.parse(text,new ParsePosition(0));
\r
833 if (!num.toString().equals("1.222"))
\r
834 errln("\"" + text + "\" is parsed as " + num);
\r
838 * DecimalFormat.format() incorrectly formats negative doubles.
\r
840 public void Test4106658()
\r
842 Locale savedLocale = Locale.getDefault();
\r
843 Locale.setDefault(Locale.US);
\r
844 DecimalFormat df = new DecimalFormat(); // Corrected; see 4147706
\r
846 double d2 = -0.0001;
\r
847 StringBuffer buffer = new StringBuffer();
\r
848 logln("pattern: \"" + df.toPattern() + "\"");
\r
849 df.format(d1, buffer, new FieldPosition(0));
\r
850 if (!buffer.toString().equals("-0")) { // Corrected; see 4147706
\r
851 errln(d1 + " is formatted as " + buffer);
\r
853 buffer.setLength(0);
\r
854 df.format(d2, buffer, new FieldPosition(0));
\r
855 if (!buffer.toString().equals("-0")) { // Corrected; see 4147706
\r
856 errln(d2 + " is formatted as " + buffer);
\r
858 Locale.setDefault(savedLocale);
\r
862 * DecimalFormat.parse returns 0 if string parameter is incorrect.
\r
864 public void Test4106662()
\r
866 DecimalFormat df = new DecimalFormat();
\r
868 ParsePosition pos1 = new ParsePosition(0), pos2 = new ParsePosition(0);
\r
870 logln("pattern: \"" + df.toPattern() + "\"");
\r
871 Number num = df.parse(text, pos1);
\r
873 errln("Test Failed: \"" + text + "\" is parsed as " + num);
\r
876 df = new DecimalFormat("$###.00");
\r
877 num = df.parse("$", pos2);
\r
879 errln("Test Failed: \"$\" is parsed as " + num);
\r
884 * NumberFormat.parse doesn't return null
\r
886 public void Test4114639()
\r
888 NumberFormat format = NumberFormat.getInstance();
\r
889 String text = "time 10:x";
\r
890 ParsePosition pos = new ParsePosition(8);
\r
891 Number result = format.parse(text, pos);
\r
892 if (result != null) errln("Should return null but got : " + result); // Should be null; it isn't
\r
896 * DecimalFormat.format(long n) fails if n * multiplier > MAX_LONG.
\r
898 public void Test4106664()
\r
900 DecimalFormat df = new DecimalFormat();
\r
901 long n = 1234567890123456L;
\r
903 BigInteger bigN = BigInteger.valueOf(n);
\r
904 bigN = bigN.multiply(BigInteger.valueOf(m));
\r
905 df.setMultiplier(m);
\r
906 df.setGroupingUsed(false);
\r
907 logln("formated: " +
\r
908 df.format(n, new StringBuffer(), new FieldPosition(0)));
\r
909 logln("expected: " + bigN.toString());
\r
912 * DecimalFormat.format incorrectly formats -0.0.
\r
914 public void Test4106667()
\r
916 Locale savedLocale = Locale.getDefault();
\r
917 Locale.setDefault(Locale.US);
\r
918 DecimalFormat df = new DecimalFormat();
\r
919 df.setPositivePrefix("+");
\r
921 logln("pattern: \"" + df.toPattern() + "\"");
\r
922 StringBuffer buffer = new StringBuffer();
\r
923 df.format(d, buffer, new FieldPosition(0));
\r
924 if (!buffer.toString().equals("-0")) { // Corrected; see 4147706
\r
925 errln(d + " is formatted as " + buffer);
\r
927 Locale.setDefault(savedLocale);
\r
931 * DecimalFormat.setMaximumIntegerDigits() works incorrectly.
\r
933 public void Test4110936()
\r
935 NumberFormat nf = NumberFormat.getInstance();
\r
936 nf.setMaximumIntegerDigits(128);
\r
937 logln("setMaximumIntegerDigits(128)");
\r
938 if (nf.getMaximumIntegerDigits() != 128)
\r
939 errln("getMaximumIntegerDigits() returns " +
\r
940 nf.getMaximumIntegerDigits());
\r
944 * Locale data should use generic currency symbol
\r
946 * 1) Make sure that all currency formats use the generic currency symbol.
\r
947 * 2) Make sure we get the same results using the generic symbol or a
\r
950 public void Test4122840()
\r
952 Locale[] locales = NumberFormat.getAvailableLocales();
\r
954 for (int i = 0; i < locales.length; i++) {
\r
955 UResourceBundle rb = UResourceBundle.getBundleInstance(ICUResourceBundle.ICU_BASE_NAME,locales[i]);
\r
958 // Get the currency pattern for this locale. We have to fish it
\r
959 // out of the ResourceBundle directly, since DecimalFormat.toPattern
\r
960 // will return the localized symbol, not \00a4
\r
962 UResourceBundle numPatterns = rb.get("NumberPatterns");
\r
963 String pattern = numPatterns.getString(1);
\r
965 if (pattern.indexOf('\u00A4') == -1 ) { // 'x' not "x" -- workaround bug in IBM JDK 1.4.1
\r
966 errln("Currency format for " + locales[i] +
\r
967 " does not contain generic currency symbol:" +
\r
971 // Create a DecimalFormat using the pattern we got and format a number
\r
972 DecimalFormatSymbols symbols = new DecimalFormatSymbols(locales[i]);
\r
973 DecimalFormat fmt1 = new DecimalFormat(pattern, symbols);
\r
975 String result1 = fmt1.format(1.111);
\r
978 // Now substitute in the locale's currency symbol and create another
\r
979 // pattern. Replace the decimal separator with the monetary separator.
\r
981 //char decSep = symbols.getDecimalSeparator(); //The variable is never used
\r
982 char monSep = symbols.getMonetaryDecimalSeparator();
\r
983 StringBuffer buf = new StringBuffer(pattern);
\r
984 for (int j = 0; j < buf.length(); j++) {
\r
985 if (buf.charAt(j) == '\u00a4') {
\r
986 String cur = "'" + symbols.getCurrencySymbol() + "'";
\r
987 buf.replace(j, j+1, cur);
\r
988 j += cur.length() - 1;
\r
991 symbols.setDecimalSeparator(monSep);
\r
992 DecimalFormat fmt2 = new DecimalFormat(buf.toString(), symbols);
\r
994 String result2 = fmt2.format(1.111);
\r
996 // NOTE: en_IN is a special case (ChoiceFormat currency display name)
\r
997 if (!result1.equals(result2) &&
\r
998 !locales[i].toString().equals("en_IN")) {
\r
999 errln("Results for " + locales[i] + " differ: " +
\r
1000 result1 + " vs " + result2);
\r
1006 * DecimalFormat.format() delivers wrong string.
\r
1008 public void Test4125885()
\r
1010 double rate = 12.34;
\r
1011 DecimalFormat formatDec = new DecimalFormat ("000.00");
\r
1012 logln("toPattern: " + formatDec.toPattern());
\r
1013 String rateString= formatDec.format(rate);
\r
1014 if (!rateString.equals("012.34"))
\r
1015 errln("result : " + rateString + " expected : 012.34");
\r
1018 formatDec = new DecimalFormat ("+000.00%;-000.00%");
\r
1019 logln("toPattern: " + formatDec.toPattern());
\r
1020 rateString= formatDec.format(rate);
\r
1021 if (!rateString.equals("+012.34%"))
\r
1022 errln("result : " + rateString + " expected : +012.34%");
\r
1027 * DecimalFormat produces extra zeros when formatting numbers.
\r
1029 public void Test4134034() {
\r
1030 DecimalFormat nf = new DecimalFormat("##,###,###.00");
\r
1032 String f = nf.format(9.02);
\r
1033 if (f.equals("9.02")) logln(f + " ok"); else errln("9.02 -> " + f + "; want 9.02");
\r
1036 if (f.equals(".00")) logln(f + " ok"); else errln("0 -> " + f + "; want .00");
\r
1040 * CANNOT REPRODUCE - This bug could not be reproduced. It may be
\r
1041 * a duplicate of 4134034.
\r
1043 * JDK 1.1.6 Bug, did NOT occur in 1.1.5
\r
1044 * Possibly related to bug 4125885.
\r
1046 * This class demonstrates a regression in version 1.1.6
\r
1047 * of DecimalFormat class.
\r
1050 * Value 1.2 Format #.00 Result '01.20' !!!wrong
\r
1051 * Value 1.2 Format 0.00 Result '001.20' !!!wrong
\r
1052 * Value 1.2 Format 00.00 Result '0001.20' !!!wrong
\r
1053 * Value 1.2 Format #0.0# Result '1.2'
\r
1054 * Value 1.2 Format #0.00 Result '001.20' !!!wrong
\r
1057 * Value 1.2 Format #.00 Result '1.20'
\r
1058 * Value 1.2 Format 0.00 Result '1.20'
\r
1059 * Value 1.2 Format 00.00 Result '01.20'
\r
1060 * Value 1.2 Format #0.0# Result '1.2'
\r
1061 * Value 1.2 Format #0.00 Result '1.20'
\r
1063 public void Test4134300() {
\r
1065 // Pattern Expected string
\r
1072 for (int i=0; i<DATA.length; i+=2) {
\r
1073 String result = new DecimalFormat(DATA[i]).format(1.2);
\r
1074 if (!result.equals(DATA[i+1])) {
\r
1075 errln("Fail: 1.2 x " + DATA[i] + " = " + result +
\r
1076 "; want " + DATA[i+1]);
\r
1079 logln("Ok: 1.2 x " + DATA[i] + " = " + result);
\r
1085 * Empty pattern produces double negative prefix.
\r
1087 public void Test4140009() {
\r
1088 final double IN[] = { 123.456, -123.456 };
\r
1089 final String OUT[] = { "123.456", "-123.456" };
\r
1090 for (int i=0; i<2; ++i) {
\r
1091 DecimalFormat f = null;
\r
1094 f = new DecimalFormat("",
\r
1095 new DecimalFormatSymbols(Locale.ENGLISH));
\r
1098 f = new DecimalFormat("#.#",
\r
1099 new DecimalFormatSymbols(Locale.ENGLISH));
\r
1100 f.applyPattern("");
\r
1103 for (int j=0; j<2; ++j) {
\r
1104 assertEquals("<empty pat " + i + ">.format(" + IN[j] + ")",
\r
1105 OUT[j], f.format(IN[j]));
\r
1110 //#if defined(FOUNDATION10)
\r
1113 * BigDecimal numbers get their fractions truncated by NumberFormat.
\r
1115 public void Test4141750() {
\r
1117 String str = "12345.67";
\r
1118 java.math.BigDecimal bd = new java.math.BigDecimal(str);
\r
1119 String sd = NumberFormat.getInstance(Locale.US).format(bd);
\r
1120 if (!sd.endsWith("67")) errln("Fail: " + str + " x format -> " + sd);
\r
1122 catch (Exception e) {
\r
1123 warnln(e.toString());
\r
1124 //e.printStackTrace();
\r
1130 * DecimalFormat toPattern() doesn't quote special characters or handle
\r
1133 public void Test4145457() {
\r
1135 DecimalFormat nf = (DecimalFormat)NumberFormat.getInstance();
\r
1136 DecimalFormatSymbols sym = nf.getDecimalFormatSymbols();
\r
1137 sym.setDecimalSeparator('\'');
\r
1138 nf.setDecimalFormatSymbols(sym);
\r
1139 double pi = 3.14159;
\r
1141 String[] PATS = { "#.00 'num''ber'", "''#.00''" };
\r
1143 for (int i=0; i<PATS.length; ++i) {
\r
1144 nf.applyPattern(PATS[i]);
\r
1145 String out = nf.format(pi);
\r
1146 String pat = nf.toPattern();
\r
1147 double val = nf.parse(out).doubleValue();
\r
1149 nf.applyPattern(pat);
\r
1150 String out2 = nf.format(pi);
\r
1151 String pat2 = nf.toPattern();
\r
1152 double val2 = nf.parse(out2).doubleValue();
\r
1154 if (!pat.equals(pat2))
\r
1155 errln("Fail with \"" + PATS[i] + "\": Patterns should concur, \"" +
\r
1156 pat + "\" vs. \"" + pat2 + "\"");
\r
1158 logln("Ok \"" + PATS[i] + "\" toPattern() -> \"" + pat + '"');
\r
1160 if (val == val2 && out.equals(out2)) {
\r
1161 logln("Ok " + pi + " x \"" + PATS[i] + "\" -> \"" +
\r
1162 out + "\" -> " + val + " -> \"" +
\r
1163 out2 + "\" -> " + val2);
\r
1166 errln("Fail " + pi + " x \"" + PATS[i] + "\" -> \"" +
\r
1167 out + "\" -> " + val + " -> \"" +
\r
1168 out2 + "\" -> " + val2);
\r
1172 catch (ParseException e) {
\r
1173 errln("Fail: " + e);
\r
1174 e.printStackTrace();
\r
1179 * DecimalFormat.applyPattern() sets minimum integer digits incorrectly.
\r
1180 * CANNOT REPRODUCE
\r
1181 * This bug is a duplicate of 4139344, which is a duplicate of 4134300
\r
1183 public void Test4147295() {
\r
1184 DecimalFormat sdf = new DecimalFormat();
\r
1185 String pattern = "#,###";
\r
1186 logln("Applying pattern \"" + pattern + "\"");
\r
1187 sdf.applyPattern(pattern);
\r
1188 int minIntDig = sdf.getMinimumIntegerDigits();
\r
1189 if (minIntDig != 0) {
\r
1190 errln("Test failed");
\r
1191 errln(" Minimum integer digits : " + minIntDig);
\r
1192 errln(" new pattern: " + sdf.toPattern());
\r
1194 logln("Test passed");
\r
1195 logln(" Minimum integer digits : " + minIntDig);
\r
1200 * DecimalFormat formats -0.0 as +0.0
\r
1201 * See also older related bug 4106658, 4106667
\r
1203 public void Test4147706() {
\r
1204 DecimalFormat df = new DecimalFormat("#,##0.0##");
\r
1205 df.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.ENGLISH));
\r
1207 double d2 = -0.0001;
\r
1208 StringBuffer f1 = df.format(d1, new StringBuffer(), new FieldPosition(0));
\r
1209 StringBuffer f2 = df.format(d2, new StringBuffer(), new FieldPosition(0));
\r
1210 if (!f1.toString().equals("-0.0")) {
\r
1211 errln(d1 + " x \"" + df.toPattern() + "\" is formatted as \"" + f1 + '"');
\r
1213 if (!f2.toString().equals("-0.0")) {
\r
1214 errln(d2 + " x \"" + df.toPattern() + "\" is formatted as \"" + f2 + '"');
\r
1219 * NumberFormat cannot format Double.MAX_VALUE
\r
1221 public void Test4162198() {
\r
1222 double dbl = Double.MAX_VALUE;
\r
1223 NumberFormat f = NumberFormat.getInstance();
\r
1224 f.setMaximumFractionDigits(Integer.MAX_VALUE);
\r
1225 f.setMaximumIntegerDigits(Integer.MAX_VALUE);
\r
1226 String s = f.format(dbl);
\r
1227 logln("The number " + dbl + " formatted to " + s);
\r
1231 } catch (java.text.ParseException e) {
\r
1232 errln("Caught a ParseException:");
\r
1233 e.printStackTrace();
\r
1235 logln("The string " + s + " parsed as " + n);
\r
1236 if (n.doubleValue() != dbl) {
\r
1237 errln("Round trip failure");
\r
1242 * NumberFormat does not parse negative zero.
\r
1244 public void Test4162852() throws ParseException {
\r
1245 for (int i=0; i<2; ++i) {
\r
1246 NumberFormat f = (i == 0) ? NumberFormat.getInstance()
\r
1247 : NumberFormat.getPercentInstance();
\r
1249 String s = f.format(d);
\r
1250 double e = f.parse(s).doubleValue();
\r
1253 '"' + s + '"' + " -> " +
\r
1255 if (e != 0.0 || 1.0/e > 0.0) {
\r
1256 logln("Failed to parse negative zero");
\r
1262 * NumberFormat truncates data
\r
1264 public void Test4167494() throws Exception {
\r
1265 NumberFormat fmt = NumberFormat.getInstance(Locale.US);
\r
1267 double a = Double.MAX_VALUE;
\r
1268 String s = fmt.format(a);
\r
1269 double b = fmt.parse(s).doubleValue();
\r
1270 boolean match = a == b;
\r
1272 logln("" + a + " -> \"" + s + "\" -> " + b + " ok");
\r
1274 errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL");
\r
1277 // We don't test Double.MIN_VALUE because the locale data for the US
\r
1278 // currently doesn't specify enough digits to display Double.MIN_VALUE.
\r
1279 // This is correct for now; however, we leave this here as a reminder
\r
1280 // in case we want to address this later.
\r
1282 a = Double.MIN_VALUE;
\r
1283 s = fmt.format(a);
\r
1284 b = fmt.parse(s).doubleValue();
\r
1287 logln("" + a + " -> \"" + s + "\" -> " + b + " ok");
\r
1289 errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL");
\r
1295 * DecimalFormat.parse() fails when ParseIntegerOnly set to true
\r
1297 public void Test4170798() {
\r
1298 Locale savedLocale = Locale.getDefault();
\r
1299 Locale.setDefault(Locale.US);
\r
1300 DecimalFormat df = new DecimalFormat();
\r
1301 df.setParseIntegerOnly(true);
\r
1302 Number n = df.parse("-0.0", new ParsePosition(0));
\r
1303 if (!(n instanceof Double)
\r
1304 || n.intValue() != 0) {
\r
1305 errln("FAIL: parse(\"-0.0\") returns " +
\r
1306 n + " (" + n.getClass().getName() + ')');
\r
1308 Locale.setDefault(savedLocale);
\r
1312 * toPattern only puts the first grouping separator in.
\r
1314 public void Test4176114() {
\r
1317 "000", "#000", // No grouping
\r
1318 "#000", "#000", // No grouping
\r
1321 "0,000", "#0,000",
\r
1322 "00,000", "#00,000",
\r
1323 "000,000", "#,000,000",
\r
1324 "0,000,000,000,000.0000", "#0,000,000,000,000.0000", // Reported
\r
1326 for (int i=0; i<DATA.length; i+=2) {
\r
1327 DecimalFormat df = new DecimalFormat(DATA[i]);
\r
1328 String s = df.toPattern();
\r
1329 if (!s.equals(DATA[i+1])) {
\r
1330 errln("FAIL: " + DATA[i] + " -> " + s + ", want " + DATA[i+1]);
\r
1336 * DecimalFormat is incorrectly rounding numbers like 1.2501 to 1.2
\r
1338 public void Test4179818() {
\r
1340 // Input Pattern Expected output
\r
1341 "1.2511", "#.#", "1.3",
\r
1342 "1.2501", "#.#", "1.3",
\r
1343 "0.9999", "#", "1",
\r
1345 DecimalFormat fmt = new DecimalFormat("#",
\r
1346 new DecimalFormatSymbols(Locale.US));
\r
1347 for (int i=0; i<DATA.length; i+=3) {
\r
1348 double in = Double.valueOf(DATA[i]).doubleValue();
\r
1349 String pat = DATA[i+1];
\r
1350 String exp = DATA[i+2];
\r
1351 fmt.applyPattern(pat);
\r
1352 String out = fmt.format(in);
\r
1353 if (out.equals(exp)) {
\r
1354 logln("Ok: " + in + " x " + pat + " = " + out);
\r
1356 errln("FAIL: " + in + " x " + pat + " = " + out +
\r
1357 ", expected " + exp);
\r
1362 public void Test4185761() throws IOException, ClassNotFoundException {
\r
1363 ByteArrayOutputStream baos = new ByteArrayOutputStream();
\r
1364 ObjectOutputStream oos = new ObjectOutputStream(baos);
\r
1366 NumberFormat nf = NumberFormat.getInstance(Locale.US);
\r
1368 // Set special values we are going to search for in the output byte stream
\r
1369 // These are all legal values.
\r
1370 nf.setMinimumIntegerDigits(0x111); // Keep under 309
\r
1371 nf.setMaximumIntegerDigits(0x112); // Keep under 309
\r
1372 nf.setMinimumFractionDigits(0x113); // Keep under 340
\r
1373 nf.setMaximumFractionDigits(0x114); // Keep under 340
\r
1375 oos.writeObject(nf);
\r
1379 byte[] bytes = baos.toByteArray();
\r
1381 // Scan for locations of min/max int/fract values in the byte array.
\r
1382 // At the moment (ICU4J 2.1), there is only one instance of each target pair
\r
1383 // in the byte stream, so assume first match is it. Note this is not entirely
\r
1384 // failsafe, and needs to be checked if we change the package or structure of
\r
1386 // Current positions are 890, 880, 886, 876
\r
1387 int[] offsets = new int[4];
\r
1388 for (int i = 0; i < bytes.length - 1; ++i) {
\r
1389 if (bytes[i] == 0x01) { // high byte
\r
1390 for (int j = 0; j < offsets.length; ++j) {
\r
1391 if ((offsets[j] == 0) && (bytes[i+1] == (0x11 + j))) { // low byte
\r
1400 ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
\r
1401 Object o = ois.readObject();
\r
1404 if (!nf.equals(o)) {
\r
1405 errln("Fail: NumberFormat serialization/equality bug");
\r
1407 logln("NumberFormat serialization/equality is OKAY.");
\r
1411 // Change the values in the byte stream so that min > max.
\r
1412 // Numberformat should catch this and throw an exception.
\r
1413 for (int i = 0; i < offsets.length; ++i) {
\r
1414 bytes[offsets[i]] = (byte)(4 - i);
\r
1418 ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
\r
1420 NumberFormat format = (NumberFormat) ois.readObject();
\r
1421 logln("format: " + format.format(1234.56)); //fix "The variable is never used"
\r
1422 errln("FAIL: Deserialized bogus NumberFormat with minXDigits > maxXDigits");
\r
1423 } catch (InvalidObjectException e) {
\r
1424 logln("Ok: " + e.getMessage());
\r
1428 // Set values so they are too high, but min <= max
\r
1429 // Format should pass the min <= max test, and DecimalFormat should reset to current maximum
\r
1430 // (for compatibility with versions streamed out before the maximums were imposed).
\r
1431 for (int i = 0; i < offsets.length; ++i) {
\r
1432 bytes[offsets[i]] = 4;
\r
1436 ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
\r
1437 NumberFormat format = (NumberFormat) ois.readObject();
\r
1438 //For compatibility with previous version
\r
1439 if ((format.getMaximumIntegerDigits() != 309)
\r
1440 || format.getMaximumFractionDigits() != 340) {
\r
1441 errln("FAIL: Deserialized bogus NumberFormat with values out of range," +
\r
1442 " intMin: " + format.getMinimumIntegerDigits() +
\r
1443 " intMax: " + format.getMaximumIntegerDigits() +
\r
1444 " fracMin: " + format.getMinimumFractionDigits() +
\r
1445 " fracMax: " + format.getMaximumFractionDigits());
\r
1447 logln("Ok: Digit count out of range");
\r
1454 * Some DecimalFormatSymbols changes are not picked up by DecimalFormat.
\r
1455 * This includes the minus sign, currency symbol, international currency
\r
1456 * symbol, percent, and permille. This is filed as bugs 4212072 and
\r
1459 public void Test4212072() throws IOException, ClassNotFoundException {
\r
1460 DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
\r
1461 DecimalFormat fmt = new DecimalFormat("#", sym);
\r
1463 sym.setMinusSign('^');
\r
1464 fmt.setDecimalFormatSymbols(sym);
\r
1465 if (!fmt.format(-1).equals("^1")) {
\r
1466 errln("FAIL: -1 x (minus=^) -> " + fmt.format(-1) +
\r
1469 if (!fmt.getNegativePrefix().equals("^")) {
\r
1470 errln("FAIL: (minus=^).getNegativePrefix -> " +
\r
1471 fmt.getNegativePrefix() + ", exp ^");
\r
1473 sym.setMinusSign('-');
\r
1475 fmt.applyPattern("#%");
\r
1476 sym.setPercent('^');
\r
1477 fmt.setDecimalFormatSymbols(sym);
\r
1478 if (!fmt.format(0.25).equals("25^")) {
\r
1479 errln("FAIL: 0.25 x (percent=^) -> " + fmt.format(0.25) +
\r
1482 if (!fmt.getPositiveSuffix().equals("^")) {
\r
1483 errln("FAIL: (percent=^).getPositiveSuffix -> " +
\r
1484 fmt.getPositiveSuffix() + ", exp ^");
\r
1486 sym.setPercent('%');
\r
1488 fmt.applyPattern("#\u2030");
\r
1489 sym.setPerMill('^');
\r
1490 fmt.setDecimalFormatSymbols(sym);
\r
1491 if (!fmt.format(0.25).equals("250^")) {
\r
1492 errln("FAIL: 0.25 x (permill=^) -> " + fmt.format(0.25) +
\r
1495 if (!fmt.getPositiveSuffix().equals("^")) {
\r
1496 errln("FAIL: (permill=^).getPositiveSuffix -> " +
\r
1497 fmt.getPositiveSuffix() + ", exp ^");
\r
1499 sym.setPerMill('\u2030');
\r
1501 fmt.applyPattern("\u00A4#.00");
\r
1502 sym.setCurrencySymbol("usd");
\r
1503 fmt.setDecimalFormatSymbols(sym);
\r
1504 if (!fmt.format(12.5).equals("usd12.50")) {
\r
1505 errln("FAIL: 12.5 x (currency=usd) -> " + fmt.format(12.5) +
\r
1506 ", exp usd12.50");
\r
1508 if (!fmt.getPositivePrefix().equals("usd")) {
\r
1509 errln("FAIL: (currency=usd).getPositivePrefix -> " +
\r
1510 fmt.getPositivePrefix() + ", exp usd");
\r
1512 sym.setCurrencySymbol("$");
\r
1514 fmt.applyPattern("\u00A4\u00A4#.00");
\r
1515 sym.setInternationalCurrencySymbol("DOL");
\r
1516 fmt.setDecimalFormatSymbols(sym);
\r
1517 if (!fmt.format(12.5).equals("DOL12.50")) {
\r
1518 errln("FAIL: 12.5 x (intlcurrency=DOL) -> " + fmt.format(12.5) +
\r
1519 ", exp DOL12.50");
\r
1521 if (!fmt.getPositivePrefix().equals("DOL")) {
\r
1522 errln("FAIL: (intlcurrency=DOL).getPositivePrefix -> " +
\r
1523 fmt.getPositivePrefix() + ", exp DOL");
\r
1525 sym.setInternationalCurrencySymbol("USD");
\r
1527 if (VersionInfo.ICU_VERSION == VersionInfo.getInstance(2,2)) {
\r
1528 // bug in 2.2 that fails this test
\r
1529 // to be fixed in the later versions
\r
1530 System.out.println("\n Test skipped for release 2.2");
\r
1534 // Since the pattern logic has changed, make sure that patterns round
\r
1535 // trip properly. Test stream in/out integrity too.
\r
1536 Locale[] avail = NumberFormat.getAvailableLocales();
\r
1537 for (int i=0; i<avail.length; ++i) {
\r
1538 for (int j=0; j<3; ++j) {
\r
1542 nf = NumberFormat.getInstance(avail[i]);
\r
1545 nf = NumberFormat.getCurrencyInstance(avail[i]);
\r
1548 nf = NumberFormat.getPercentInstance(avail[i]);
\r
1551 DecimalFormat df = (DecimalFormat) nf;
\r
1553 // Test toPattern/applyPattern round trip
\r
1554 String pat = df.toPattern();
\r
1555 DecimalFormatSymbols symb = new DecimalFormatSymbols(avail[i]);
\r
1556 DecimalFormat f2 = new DecimalFormat(pat, symb);
\r
1557 if (!df.equals(f2)) {
\r
1558 errln("FAIL: " + avail[i] + " #" + j + " -> \"" + pat +
\r
1559 "\" -> \"" + f2.toPattern() + '"');
\r
1562 // Test toLocalizedPattern/applyLocalizedPattern round trip
\r
1563 pat = df.toLocalizedPattern();
\r
1565 f2.applyLocalizedPattern(pat);
\r
1567 String s1 = f2.format(123456);
\r
1568 String s2 = df.format(123456);
\r
1569 if(!s1.equals(s2)){
\r
1570 errln("FAIL: " + avail[i] + " #" + j + " -> localized \"" + s2 +
\r
1571 "\" -> \"" + s2 + '"'+ " in locale "+df.getLocale(ULocale.ACTUAL_LOCALE));
\r
1574 if (!df.equals(f2)) {
\r
1575 errln("FAIL: " + avail[i] + " #" + j + " -> localized \"" + pat +
\r
1576 "\" -> \"" + f2.toLocalizedPattern() + '"'+ " in locale "+df.getLocale(ULocale.ACTUAL_LOCALE));
\r
1577 errln("s1: "+s1+" s2: "+s2);
\r
1580 }catch(IllegalArgumentException ex){
\r
1581 errln(ex.getMessage()+" for locale "+ df.getLocale(ULocale.ACTUAL_LOCALE));
\r
1585 // Test writeObject/readObject round trip
\r
1586 ByteArrayOutputStream baos = new ByteArrayOutputStream();
\r
1587 ObjectOutputStream oos = new ObjectOutputStream(baos);
\r
1588 oos.writeObject(df);
\r
1591 byte[] bytes = baos.toByteArray();
\r
1592 ObjectInputStream ois =
\r
1593 new ObjectInputStream(new ByteArrayInputStream(bytes));
\r
1594 f2 = (DecimalFormat) ois.readObject();
\r
1595 if (!df.equals(f2)) {
\r
1596 errln("FAIL: Stream in/out " + avail[i] + " -> \"" + pat +
\r
1598 (f2 != null ? ("\""+f2.toPattern()+'"') : "null"));
\r
1605 // Make sure that all special characters, when quoted in a suffix or
\r
1606 // prefix, lose their special meaning.
\r
1607 char[] SPECIALS = { '0', ',', '.', '\u2030', '%', '#',
\r
1608 ';', 'E', '*', '+', '-' };
\r
1609 sym = new DecimalFormatSymbols(Locale.US);
\r
1610 for (int j=0; j<SPECIALS.length; ++j) {
\r
1611 char special = SPECIALS[j];
\r
1612 String pat = "'" + special + "'#0'" + special + "'";
\r
1614 fmt = new DecimalFormat(pat, sym);
\r
1615 String pat2 = fmt.toPattern();
\r
1616 if (!pat.equals(pat2)) {
\r
1617 errln("FAIL: Pattern \"" + pat + "\" => toPattern() => \"" +
\r
1620 String s = fmt.format(123);
\r
1621 String exp = "" + special + "123" + special;
\r
1622 if (!s.equals(exp)) {
\r
1623 errln("FAIL: 123 x \"" + pat + "\" => \"" + s + "\", exp \"" +
\r
1626 } catch (IllegalArgumentException e) {
\r
1627 errln("FAIL: Pattern \"" + pat + "\" => " + e.getMessage());
\r
1633 * DecimalFormat.parse() fails for mulipliers 2^n.
\r
1635 public void Test4216742() throws ParseException {
\r
1636 DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance(Locale.US);
\r
1637 long[] DATA = { Long.MIN_VALUE, Long.MAX_VALUE, -100000000L, 100000000L};
\r
1638 for (int i=0; i<DATA.length; ++i) {
\r
1639 String str = Long.toString(DATA[i]);
\r
1640 for (int m = 1; m <= 100; m++) {
\r
1641 fmt.setMultiplier(m);
\r
1642 long n = ((Number) fmt.parse(str)).longValue();
\r
1643 if (n > 0 != DATA[i] > 0) {
\r
1644 errln("\"" + str + "\" parse(x " + fmt.getMultiplier() +
\r
1652 * DecimalFormat formats 1.001 to "1.00" instead of "1" with 2 fraction
\r
1655 public void Test4217661() {
\r
1657 new Double(0.001), "0",
\r
1658 new Double(1.001), "1",
\r
1659 new Double(0.006), "0.01",
\r
1660 new Double(1.006), "1.01",
\r
1662 NumberFormat fmt = NumberFormat.getInstance(Locale.US);
\r
1663 fmt.setMaximumFractionDigits(2);
\r
1664 for (int i=0; i<DATA.length; i+=2) {
\r
1665 String s = fmt.format(((Double) DATA[i]).doubleValue());
\r
1666 if (!s.equals(DATA[i+1])) {
\r
1667 errln("FAIL: Got " + s + ", exp " + DATA[i+1]);
\r
1673 * 4243011: Formatting .5 rounds to "1" instead of "0"
\r
1675 public void Test4243011() {
\r
1676 double DATA[] = {0.5, 1.5, 2.5, 3.5, 4.5};
\r
1677 String EXPECTED[] = {"0.", "2.", "2.", "4.", "4."};
\r
1679 DecimalFormat format = new DecimalFormat("0.");
\r
1680 for (int i = 0; i < DATA.length; i++) {
\r
1681 String result = format.format(DATA[i]);
\r
1682 if (result.equals(EXPECTED[i])) {
\r
1683 logln("OK: got " + result);
\r
1685 errln("FAIL: got " + result);
\r
1691 * 4243108: format(0.0) gives "0.1" if preceded by parse("99.99")
\r
1693 public void Test4243108() {
\r
1694 DecimalFormat f = new DecimalFormat("#.#");
\r
1695 String result = f.format(0.0);
\r
1696 if (result.equals("0")) {
\r
1697 logln("OK: got " + result);
\r
1699 errln("FAIL: got " + result);
\r
1702 double dResult = f.parse("99.99").doubleValue();
\r
1703 if (dResult == 99.99) {
\r
1704 logln("OK: got " + dResult);
\r
1706 errln("FAIL: got " + dResult);
\r
1708 } catch (ParseException e) {
\r
1709 errln("Caught a ParseException:");
\r
1710 e.printStackTrace();
\r
1712 result = f.format(0.0);
\r
1713 if (result.equals("0")) {
\r
1714 logln("OK: got " + result);
\r
1716 errln("FAIL: got " + result);
\r
1721 * 4330377: DecimalFormat engineering notation gives incorrect results
\r
1723 public void test4330377() {
\r
1725 double[] input = {5000.0, 500.0, 50.0, 5.0, 0.5, 0.05, 0.005, 0.0005,
\r
1726 5050.0, 505.0, 50.5, 5.05, 0.505, 0.0505, 0.00505, 0.000505};
\r
1727 String[] pattern = {"000.#E0", "##0.#E0", "#00.#E0"};
\r
1728 String[][] expected = {
\r
1729 // it's questionable whether "#00.#E0" should result in post-decimal
\r
1730 // zeroes, i.e., whether "5.0E3", "5.0E0", "5.0E-3" are really good
\r
1731 {"500E1", "5E3", "5.0E3"},
\r
1732 {"500E0", "500E0", "500E0"},
\r
1733 {"500E-1", "50E0", "50E0"},
\r
1734 {"500E-2", "5E0", "5.0E0"},
\r
1735 {"500E-3", "500E-3", "500E-3"},
\r
1736 {"500E-4", "50E-3", "50E-3"},
\r
1737 {"500E-5", "5E-3", "5.0E-3"},
\r
1738 {"500E-6", "500E-6", "500E-6"},
\r
1739 {"505E1", "5.05E3", "5.05E3"},
\r
1740 {"505E0", "505E0", "505E0"},
\r
1741 {"505E-1", "50.5E0", "50.5E0"},
\r
1742 {"505E-2", "5.05E0", "5.05E0"},
\r
1743 {"505E-3", "505E-3", "505E-3"},
\r
1744 {"505E-4", "50.5E-3", "50.5E-3"},
\r
1745 {"505E-5", "5.05E-3", "5.05E-3"},
\r
1746 {"505E-6", "505E-6", "505E-6"}
\r
1748 for (int i = 0; i < input.length; i++) {
\r
1749 for (int j = 0; j < pattern.length; j++) {
\r
1750 DecimalFormat format = new DecimalFormat(pattern[j]);
\r
1751 String result = format.format(input[i]);
\r
1752 if (!result.equals(expected[i][j])) {
\r
1753 errln("FAIL: input: " + input[i] +
\r
1754 ", pattern: " + pattern[j] +
\r
1755 ", expected: " + expected[i][j] +
\r
1756 ", got: " + result);
\r
1764 * 4233840: NumberFormat does not round correctly
\r
1766 public void test4233840() {
\r
1767 float f = 0.0099f;
\r
1769 NumberFormat nf = new DecimalFormat("0.##", new DecimalFormatSymbols(Locale.US));
\r
1770 nf.setMinimumFractionDigits(2);
\r
1772 String result = nf.format(f);
\r
1774 if (!result.equals("0.01")) {
\r
1775 errln("FAIL: input: " + f + ", expected: 0.01, got: " + result);
\r
1780 * 4241880: Decimal format doesnt round a double properly when the number is less than 1
\r
1782 public void test4241880() {
\r
1783 Locale savedLocale = Locale.getDefault();
\r
1784 Locale.setDefault(Locale.US);
\r
1785 double[] input = {
\r
1786 .019, .009, .015, .016, .014,
\r
1787 .004, .005, .006, .007, .008,
\r
1788 .5, 1.5, .05, .15, .005,
\r
1789 .015, .0005, .0015,
\r
1791 String[] pattern = {
\r
1792 "##0%", "##0%", "##0%", "##0%", "##0%",
\r
1793 "##0%", "##0%", "##0%", "##0%", "##0%",
\r
1794 "#,##0", "#,##0", "#,##0.0", "#,##0.0", "#,##0.00",
\r
1795 "#,##0.00", "#,##0.000", "#,##0.000",
\r
1797 String[] expected = {
\r
1798 "2%", "1%", "2%", "2%", "1%",
\r
1799 "0%", "0%", "1%", "1%", "1%",
\r
1800 "0", "2", "0.0", "0.2", "0.00",
\r
1801 "0.02", "0.000", "0.002",
\r
1803 for (int i = 0; i < input.length; i++) {
\r
1804 DecimalFormat format = new DecimalFormat(pattern[i]);
\r
1805 String result = format.format(input[i]);
\r
1806 if (!result.equals(expected[i])) {
\r
1807 errln("FAIL: input: " + input[i] +
\r
1808 ", pattern: " + pattern[i] +
\r
1809 ", expected: " + expected[i] +
\r
1810 ", got: " + result);
\r
1813 Locale.setDefault(savedLocale);
\r
1817 class myformat implements Serializable
\r
1820 * For serialization
\r
1822 private static final long serialVersionUID = 4120813612616076506L;
\r
1823 DateFormat _dateFormat = DateFormat.getDateInstance();
\r
1825 public String Now()
\r
1827 GregorianCalendar calendar = new GregorianCalendar();
\r
1828 Date t = calendar.getTime();
\r
1829 String nowStr = _dateFormat.format(t);
\r
1834 class MyNumberFormatTest extends NumberFormat {
\r
1836 * For serialization
\r
1838 private static final long serialVersionUID = 1251303884737169952L;
\r
1839 public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {
\r
1840 return new StringBuffer("");
\r
1842 public StringBuffer format(long number,StringBuffer toAppendTo, FieldPosition pos) {
\r
1843 return new StringBuffer("");
\r
1845 public Number parse(String text, ParsePosition parsePosition) {
\r
1846 return new Integer(0);
\r
1848 //#if defined(FOUNDATION10)
\r
1850 public StringBuffer format(java.math.BigDecimal number, StringBuffer toAppendTo, FieldPosition pos) {
\r
1851 return new StringBuffer("");
\r
1854 public StringBuffer format(BigInteger number, StringBuffer toAppendTo, FieldPosition pos) {
\r
1855 return new StringBuffer("");
\r
1857 public StringBuffer format(com.ibm.icu.math.BigDecimal number, StringBuffer toAppendTo, FieldPosition pos) {
\r
1858 return new StringBuffer("");
\r