]> gitweb.fperrin.net Git - Dictionary.git/blob - jars/icu4j-4_2_1-src/src/com/ibm/icu/dev/test/format/NumberRegression.java
icu4jsrc
[Dictionary.git] / jars / icu4j-4_2_1-src / src / com / ibm / icu / dev / test / format / NumberRegression.java
1 //##header\r
2 /*****************************************************************************************\r
3  *\r
4  * Copyright (C) 1996-2009, International Business Machines\r
5  * Corporation and others.  All Rights Reserved.\r
6  **/\r
7 \r
8 /** \r
9  * Port From:   JDK 1.4b1 : java.text.Format.NumberRegression\r
10  * Source File: java/text/format/NumberRegression.java\r
11  **/\r
12  \r
13 /**\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
23  */\r
24 \r
25 package com.ibm.icu.dev.test.format;\r
26 \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
31 \r
32 import java.io.*;\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
39 \r
40 public class NumberRegression extends com.ibm.icu.dev.test.TestFmwk {\r
41 \r
42     public static void main(String[] args) throws Exception {\r
43         new NumberRegression().run(args);\r
44     }\r
45 \r
46     private static final char EURO = '\u20ac';\r
47 \r
48     /**\r
49      * NumberFormat.equals comparing with null should always return false.\r
50      */\r
51     public void Test4075713(){\r
52 \r
53         try {\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
59         }\r
60     }\r
61 \r
62     /**\r
63      * NumberFormat.equals comparing two obj equal even the setGroupingUsed\r
64      * flag is different.\r
65      */\r
66     public void Test4074620() {\r
67 \r
68         MyNumberFormatTest nf1 = new MyNumberFormatTest();\r
69         MyNumberFormatTest nf2 = new MyNumberFormatTest();\r
70 \r
71         nf1.setGroupingUsed(false);\r
72         nf2.setGroupingUsed(true);\r
73 \r
74         if (nf1.equals(nf2)) errln("Test for bug 4074620 failed");\r
75         else logln("Test for bug 4074620 passed.");\r
76         return;\r
77     }\r
78 \r
79 \r
80     /**\r
81      * DecimalFormat.format() incorrectly uses maxFractionDigits setting.\r
82      */\r
83 \r
84     public void Test4088161 (){\r
85         DecimalFormat df = new DecimalFormat();\r
86         double d = 100;\r
87         df.setMinimumFractionDigits(0);\r
88         df.setMaximumFractionDigits(16);\r
89         StringBuffer sBuf1 = new StringBuffer("");\r
90         FieldPosition fp1 = new FieldPosition(0);\r
91         logln("d = " + d);\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
101     }\r
102     /**\r
103      * DecimalFormatSymbols should be cloned in the ctor DecimalFormat.\r
104      * DecimalFormat(String, DecimalFormatSymbols).\r
105      */\r
106     public void Test4087245 (){\r
107         DecimalFormatSymbols symbols = new DecimalFormatSymbols();\r
108         DecimalFormat df = new DecimalFormat("#,##0.0", symbols);\r
109         long n = 123;\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
119     }\r
120     /**\r
121      * DecimalFormat.format() incorrectly formats 0.0\r
122      */\r
123     public void Test4087535 ()\r
124     {\r
125         DecimalFormat df = new DecimalFormat();\r
126         df.setMinimumIntegerDigits(0);\r
127 \r
128         double n = 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
133         n = 0.1;\r
134         buffer = df.format(n);\r
135         if (buffer.length() == 0)\r
136             errln(n + ": '" + buffer + "'");\r
137     }\r
138 \r
139     /**\r
140      * DecimalFormat.format fails when groupingSize is set to 0.\r
141      */\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
147         try {\r
148             logln(df.format(123, sBuf, fp).toString());\r
149         } catch (Exception foo) {\r
150             errln("Test for bug 4088503 failed.");\r
151         }\r
152 \r
153     }\r
154     /**\r
155      * NumberFormat.getCurrencyInstance is wrong.\r
156      */\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
163     }\r
164 \r
165     public float assignFloatValue(float returnfloat)\r
166     {\r
167         logln(" VALUE " + returnfloat);\r
168         NumberFormat nfcommon =  NumberFormat.getCurrencyInstance(Locale.US);\r
169         nfcommon.setGroupingUsed(false);\r
170 \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
176 \r
177     /**\r
178      * DecimalFormat throws exception when parsing "0"\r
179      */\r
180     public void Test4059870() {\r
181         DecimalFormat format = new DecimalFormat("00");\r
182         try {\r
183             logln(format.parse("0").toString());\r
184         } catch (Exception e) { errln("Test for bug 4059870 failed : " + e); }\r
185     }\r
186     /**\r
187      * DecimalFormatSymbol.equals should always return false when\r
188      * comparing with null.\r
189      */\r
190 \r
191     public void Test4083018 (){\r
192         DecimalFormatSymbols dfs = new DecimalFormatSymbols();\r
193         try {\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
198         }\r
199     }\r
200     /**\r
201      * DecimalFormat does not round up correctly.\r
202      */\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
212     }\r
213 \r
214     /**\r
215      * A space as a group separator for localized pattern causes\r
216      * wrong format.  WorkAround : use non-breaking space.\r
217      */\r
218     public void Test4086575() {\r
219 \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
223 \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
229 \r
230         logln("nf: " + nf.format(1234)); // 1234,00\r
231         logln("nf: " + nf.format(-1234)); // (1234,00)\r
232 \r
233         // Space as group separator\r
234 \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
245 \r
246         // Erroneously prints:\r
247         // 1234,00 ,\r
248         // (1234,00 ,)\r
249 \r
250     }\r
251     /**\r
252      * DecimalFormat.parse returns wrong value\r
253      */\r
254     public void Test4068693()\r
255     {\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
262         }\r
263     }\r
264 \r
265     /* bugs 4069754, 4067878\r
266      * null pointer thrown when accessing a deserialized DecimalFormat\r
267      * object.\r
268      */\r
269     public void Test4069754() throws Exception\r
270     {\r
271         //try {\r
272             ByteArrayOutputStream baos = new ByteArrayOutputStream();\r
273             ObjectOutputStream oos = new ObjectOutputStream(baos);\r
274             myformat it = new myformat();\r
275             logln(it.Now());\r
276             oos.writeObject(it);\r
277             oos.flush();\r
278             baos.close();\r
279             logln("Save OK!");\r
280             byte [] bytes = baos.toByteArray();\r
281             ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));\r
282             myformat o = (myformat)ois.readObject();\r
283             ois.close();\r
284             it.Now();\r
285             logln("Load OK!");\r
286             if (!o._dateFormat.equals(it._dateFormat)) {\r
287                 throw new Exception("The saved and loaded object are not equals!");\r
288             }\r
289             logln("Compare OK!");\r
290         //} catch (Exception foo) {\r
291             //errln("Test for bug 4069754 or 4057878 failed => Exception: " + foo.getMessage());\r
292         //}\r
293     }\r
294 \r
295     /**\r
296      * DecimalFormat.applyPattern(String) allows illegal patterns\r
297      */\r
298     public void Test4087251 (){\r
299         DecimalFormat df = new DecimalFormat();\r
300         try {\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
306         }\r
307         // Second test; added 5/11/98 when reported to fail on 1.2b3\r
308         try {\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
314         }\r
315     }\r
316 \r
317     /**\r
318      * DecimalFormat.format() loses precision\r
319      */\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
328         logln("d = " + d);\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
333         }\r
334     }\r
335 \r
336     /**\r
337      * DecimalFormat.format() loses precision\r
338      */\r
339     public void Test4090504 ()\r
340     {\r
341         double d = 1;\r
342         logln("d = " + d);\r
343         DecimalFormat df = new DecimalFormat();\r
344         StringBuffer sb;\r
345         FieldPosition fp;\r
346         try {\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
353             }\r
354         } catch (Exception foo) {\r
355             errln("Bug 4090504 regression test failed. Message : " + foo.getMessage());\r
356         }\r
357     }\r
358     /**\r
359      * DecimalFormat.parse(String str, ParsePosition pp) loses precision\r
360      */\r
361     public void Test4095713 ()\r
362     {\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
370     }\r
371 \r
372     /**\r
373      * DecimalFormat.parse() fails when multiplier is not set to 1\r
374      */\r
375     public void Test4092561 ()\r
376     {\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
386         }\r
387         Locale.setDefault(savedLocale);\r
388     }\r
389 \r
390     /**\r
391      * DecimalFormat: Negative format ignored.\r
392      */\r
393     public void Test4092480 ()\r
394     {\r
395         DecimalFormat dfFoo = new DecimalFormat("000");\r
396 \r
397         try {\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
408 \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
414 \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
422         }\r
423     }\r
424     /**\r
425      * NumberFormat.getCurrencyInstance() produces format that uses\r
426      * decimal separator instead of monetary decimal separator.\r
427      *\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
431      */\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
443         } else {\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
452             } else {\r
453                 errln("FAIL: 1.23 -> \"" + str + "\", should contain \"" +\r
454                       monStr +\r
455                       "\" and not \"" + decStr + '"');\r
456             }\r
457         }\r
458     }\r
459     /**\r
460      * Number format data rounding errors for locale FR\r
461      */\r
462     public void Test4070798 () {\r
463         NumberFormat formatter;\r
464         String tempString;\r
465         /* User error :\r
466         String expectedDefault = "-5\u00a0789,987";\r
467         String expectedCurrency = "5\u00a0789,98\u00a0F";\r
468         String expectedPercent = "-578\u00a0998%";\r
469         */\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
473 \r
474         formatter = NumberFormat.getNumberInstance(Locale.FRANCE);\r
475         tempString = formatter.format (-5789.9876);\r
476 \r
477         if (tempString.equals(expectedDefault)) {\r
478             logln ("Bug 4070798 default test passed.");\r
479         } else {\r
480             errln("Failed:" +\r
481             " Expected " + expectedDefault +\r
482             " Received " + tempString );\r
483         }\r
484 \r
485 \r
486         formatter = NumberFormat.getCurrencyInstance(Locale.FRANCE);\r
487         tempString = formatter.format( 5789.9876 );\r
488 \r
489         if (tempString.equals(expectedCurrency) ) {\r
490             logln ("Bug 4070798 currency test assed.");\r
491         } else {\r
492             errln("Failed:" +\r
493             " Expected " + expectedCurrency +\r
494             " Received " + tempString );\r
495         }\r
496 \r
497 \r
498         formatter = NumberFormat.getPercentInstance(Locale.FRANCE);\r
499         tempString = formatter.format (-5789.9876);\r
500 \r
501         if (tempString.equals(expectedPercent) ) {\r
502             logln ("Bug 4070798 percentage test passed.");\r
503         } else {\r
504             errln("Failed:" +\r
505             " Expected " + expectedPercent +\r
506             " Received " + tempString );\r
507         }\r
508     }\r
509     /**\r
510      * Data rounding errors for French (Canada) locale\r
511      */\r
512     public void Test4071005 () {\r
513 \r
514         NumberFormat formatter;\r
515         String tempString;\r
516     /* user error :\r
517         String expectedDefault = "-5 789,987";\r
518         String expectedCurrency = "5 789,98\u00a0$";\r
519         String expectedPercent = "-578 998%";\r
520     */\r
521         String expectedDefault = "-5\u00a0789,988";\r
522         String expectedCurrency = "5\u00a0789,99\u00a0$";\r
523         String expectedPercent = "-578\u00a0999\u00A0%";\r
524 \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
529         } else {\r
530             errln("Failed:" +\r
531             " Expected " + expectedDefault +\r
532             " Received " + tempString );\r
533         }\r
534 \r
535         formatter = NumberFormat.getCurrencyInstance(Locale.CANADA_FRENCH);\r
536         tempString = formatter.format( 5789.9876 ) ;\r
537 \r
538         if (tempString.equals(expectedCurrency) ) {\r
539             logln ("Bug 4071005 currency test passed.");\r
540         } else {\r
541             errln("Failed:" +\r
542             " Expected " + expectedCurrency +\r
543             " Received " + tempString );\r
544         }\r
545         formatter = NumberFormat.getPercentInstance(Locale.CANADA_FRENCH);\r
546         tempString = formatter.format (-5789.9876);\r
547 \r
548         if (tempString.equals(expectedPercent) ) {\r
549             logln ("Bug 4071005 percentage test passed.");\r
550         } else {\r
551             errln("Failed:" +\r
552             " Expected " + expectedPercent +\r
553             " Received " + tempString );\r
554         }\r
555     }\r
556 \r
557     /**\r
558      * Data rounding errors for German (Germany) locale\r
559      */\r
560     public void Test4071014 () {\r
561         NumberFormat formatter;\r
562         String tempString;\r
563         /* user error :\r
564         String expectedDefault = "-5.789,987";\r
565         String expectedCurrency = "5.789,98\u00a0DM";\r
566         String expectedPercent = "-578.998%";\r
567         */\r
568         String expectedDefault = "-5.789,988";\r
569         String expectedCurrency = "5.789,99\u00a0" + EURO;\r
570         String expectedPercent = "-578.999\u00a0%";\r
571 \r
572         formatter = NumberFormat.getNumberInstance(Locale.GERMANY);\r
573         tempString = formatter.format (-5789.9876);\r
574 \r
575         if (tempString.equals(expectedDefault)) {\r
576             logln ("Bug 4071014 default test passed.");\r
577         } else {\r
578             errln("Failed:" +\r
579             " Expected " + expectedDefault +\r
580             " Received " + tempString );\r
581         }\r
582 \r
583         formatter = NumberFormat.getCurrencyInstance(Locale.GERMANY);\r
584         tempString = formatter.format( 5789.9876 ) ;\r
585 \r
586         if (tempString.equals(expectedCurrency) ) {\r
587             logln ("Bug 4071014 currency test passed.");\r
588         } else {\r
589             errln("Failed:" +\r
590             " Expected " + expectedCurrency +\r
591             " Received " + tempString );\r
592         }\r
593 \r
594         formatter = NumberFormat.getPercentInstance(Locale.GERMANY);\r
595         tempString = formatter.format (-5789.9876);\r
596 \r
597         if (tempString.equals(expectedPercent) ) {\r
598             logln ("Bug 4071014 percentage test passed.");\r
599         } else {\r
600             errln("Failed:" +\r
601             " Expected " + expectedPercent +\r
602             " Received " + tempString );\r
603         }\r
604 \r
605     }\r
606     /**\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
609      */\r
610     public void Test4071859 () {\r
611         NumberFormat formatter;\r
612         String tempString;\r
613         /* user error :\r
614         String expectedDefault = "-5.789,987";\r
615         String expectedCurrency = "-L.\u00a05.789,98";\r
616         String expectedPercent = "-578.998%";\r
617         */\r
618         String expectedDefault = "-5.789,988";\r
619         String expectedCurrency = "-" + EURO + "\u00a05.789,99";\r
620         String expectedPercent = "-578.999%";\r
621 \r
622         formatter = NumberFormat.getNumberInstance(Locale.ITALY);\r
623         tempString = formatter.format (-5789.9876);\r
624 \r
625         if (tempString.equals(expectedDefault)) {\r
626             logln ("Bug 4071859 default test passed.");\r
627         } else {\r
628             errln("a) Failed:" +\r
629             " Expected " + expectedDefault +\r
630             " Received " + tempString );\r
631         }\r
632 \r
633         formatter = NumberFormat.getCurrencyInstance(Locale.ITALY);\r
634         tempString = formatter.format( -5789.9876 ) ;\r
635 \r
636         if (tempString.equals(expectedCurrency) ) {\r
637             logln ("Bug 4071859 currency test passed.");\r
638         } else {\r
639             errln("b) Failed:" +\r
640             " Expected " + expectedCurrency +\r
641             " Received " + tempString );\r
642         }\r
643 \r
644         formatter = NumberFormat.getPercentInstance(Locale.ITALY);\r
645         tempString = formatter.format (-5789.9876);\r
646 \r
647         if (tempString.equals(expectedPercent) ) {\r
648             logln ("Bug 4071859 percentage test passed.");\r
649         } else {\r
650             errln("c) Failed:" +\r
651             " Expected " + expectedPercent +\r
652             " Received " + tempString );\r
653         }\r
654 \r
655     }\r
656     /* bug 4071859\r
657      * Test rounding for nearest even.\r
658      */\r
659     public void Test4093610()\r
660     {\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
674 \r
675     }\r
676     void roundingTest(DecimalFormat df, double x, String expected)\r
677     {\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
681     }\r
682     /**\r
683      * Tests the setMaximumFractionDigits limit.\r
684      */\r
685     public void Test4098741()\r
686     {\r
687         try {\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
693         }\r
694     }\r
695     /**\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
699      */\r
700     public void Test4074454()\r
701     {\r
702         try {\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
712         }\r
713     }\r
714     /**\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
720      * [3] Fixed.\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
725      * will be thrown.\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
732      */\r
733     public void Test4099404()\r
734     {\r
735         try {\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
741         }\r
742         try {\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
748         }\r
749     }\r
750     /**\r
751      * DecimalFormat.applyPattern doesn't set minimum integer digits\r
752      */\r
753     public void Test4101481()\r
754     {\r
755         DecimalFormat sdf = new DecimalFormat("#,##0");\r
756         if (sdf.getMinimumIntegerDigits() != 1)\r
757             errln("Minimum integer digits : " + sdf.getMinimumIntegerDigits());\r
758     }\r
759     /**\r
760      * Tests ParsePosition.setErrorPosition() and ParsePosition.getErrorPosition().\r
761      */\r
762     public void Test4052223()\r
763     {\r
764         try {\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
770         }\r
771     }\r
772     /**\r
773      * API tests for API addition request A9.\r
774      */\r
775     public void Test4061302()\r
776     {\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
785         }\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
797         }\r
798         logln("After set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator);\r
799     }\r
800     /**\r
801      * API tests for API addition request A23. FieldPosition.getBeginIndex and\r
802      * FieldPosition.getEndIndex.\r
803      */\r
804     public void Test4062486()\r
805     {\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
817     }\r
818 \r
819     /**\r
820      * DecimalFormat.parse incorrectly works with a group separator.\r
821      */\r
822     public void Test4108738()\r
823     {\r
824 \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
835     }\r
836 \r
837     /**\r
838      * DecimalFormat.format() incorrectly formats negative doubles.\r
839      */\r
840     public void Test4106658()\r
841     {\r
842         Locale savedLocale = Locale.getDefault();\r
843         Locale.setDefault(Locale.US);\r
844         DecimalFormat df = new DecimalFormat(); // Corrected; see 4147706\r
845         double d1 = -0.0;\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
852         }\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
857         }\r
858         Locale.setDefault(savedLocale);\r
859     }\r
860 \r
861     /**\r
862      * DecimalFormat.parse returns 0 if string parameter is incorrect.\r
863      */\r
864     public void Test4106662()\r
865     {\r
866         DecimalFormat df = new DecimalFormat();\r
867         String text = "x";\r
868         ParsePosition pos1 = new ParsePosition(0), pos2 = new ParsePosition(0);\r
869 \r
870         logln("pattern: \"" + df.toPattern() + "\"");\r
871         Number num = df.parse(text, pos1);\r
872         if (num != null) {\r
873             errln("Test Failed: \"" + text + "\" is parsed as " + num);\r
874         }\r
875         df = null;\r
876         df = new DecimalFormat("$###.00");\r
877         num = df.parse("$", pos2);\r
878         if (num != null){\r
879             errln("Test Failed: \"$\" is parsed as " + num);\r
880         }\r
881     }\r
882 \r
883     /**\r
884      * NumberFormat.parse doesn't return null\r
885      */\r
886     public void Test4114639()\r
887     {\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
893     }\r
894 \r
895     /**\r
896      * DecimalFormat.format(long n) fails if n * multiplier > MAX_LONG.\r
897      */\r
898     public void Test4106664()\r
899     {\r
900         DecimalFormat df = new DecimalFormat();\r
901         long n = 1234567890123456L;\r
902         int m = 12345678;\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
910     }\r
911     /**\r
912      * DecimalFormat.format incorrectly formats -0.0.\r
913      */\r
914     public void Test4106667()\r
915     {\r
916         Locale savedLocale = Locale.getDefault();\r
917         Locale.setDefault(Locale.US);\r
918         DecimalFormat df = new DecimalFormat();\r
919         df.setPositivePrefix("+");\r
920         double d = -0.0;\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
926         }\r
927         Locale.setDefault(savedLocale);\r
928     }\r
929 \r
930     /**\r
931      * DecimalFormat.setMaximumIntegerDigits() works incorrectly.\r
932      */\r
933     public void Test4110936()\r
934     {\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
941     }\r
942     \r
943     /**\r
944      * Locale data should use generic currency symbol\r
945      *\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
948      *    hard-coded one.\r
949      */\r
950     public void Test4122840()\r
951     {\r
952         Locale[] locales = NumberFormat.getAvailableLocales();\r
953         \r
954         for (int i = 0; i < locales.length; i++) {\r
955             UResourceBundle rb = UResourceBundle.getBundleInstance(ICUResourceBundle.ICU_BASE_NAME,locales[i]);\r
956 \r
957             //\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
961             //\r
962             UResourceBundle numPatterns = rb.get("NumberPatterns");\r
963             String pattern = numPatterns.getString(1);\r
964             \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
968                         pattern );\r
969             }\r
970             \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
974             \r
975             String result1 = fmt1.format(1.111);\r
976             \r
977             //\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
980             //\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
989                 }\r
990             }\r
991             symbols.setDecimalSeparator(monSep);\r
992             DecimalFormat fmt2 = new DecimalFormat(buf.toString(), symbols);\r
993             \r
994             String result2 = fmt2.format(1.111);\r
995             \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
1001             }\r
1002         }\r
1003     }\r
1004      \r
1005     /**\r
1006      * DecimalFormat.format() delivers wrong string.\r
1007      */\r
1008     public void Test4125885()\r
1009     {\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
1016         rate = 0.1234;\r
1017         formatDec = null;\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
1023     }\r
1024 \r
1025     /**\r
1026      **\r
1027      * DecimalFormat produces extra zeros when formatting numbers.\r
1028      */\r
1029     public void Test4134034() {\r
1030         DecimalFormat nf = new DecimalFormat("##,###,###.00");\r
1031         \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
1034 \r
1035         f = nf.format(0);\r
1036         if (f.equals(".00")) logln(f + " ok"); else errln("0 -> " + f + "; want .00");\r
1037     }\r
1038 \r
1039     /**\r
1040      * CANNOT REPRODUCE - This bug could not be reproduced.  It may be\r
1041      * a duplicate of 4134034.\r
1042      *\r
1043      * JDK 1.1.6 Bug, did NOT occur in 1.1.5\r
1044      * Possibly related to bug 4125885.\r
1045      * \r
1046      * This class demonstrates a regression in version 1.1.6\r
1047      * of DecimalFormat class.\r
1048      * \r
1049      * 1.1.6 Results\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
1055      * \r
1056      * 1.1.5 Results\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
1062      */\r
1063     public void Test4134300() {\r
1064         String[] DATA = {\r
1065          // Pattern      Expected string\r
1066             "#.00",      "1.20",\r
1067             "0.00",      "1.20",\r
1068             "00.00",     "01.20",\r
1069             "#0.0#",     "1.2",\r
1070             "#0.00",     "1.20",\r
1071         };\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
1077             }\r
1078             else {\r
1079                 logln("Ok: 1.2 x " + DATA[i] + " = " + result);\r
1080             }\r
1081         }\r
1082     }\r
1083 \r
1084     /**\r
1085      * Empty pattern produces double negative prefix.\r
1086      */\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
1092             switch (i) {\r
1093             case 0:\r
1094                 f = new DecimalFormat("",\r
1095                             new DecimalFormatSymbols(Locale.ENGLISH));\r
1096                 break;\r
1097             case 1:\r
1098                 f = new DecimalFormat("#.#",\r
1099                             new DecimalFormatSymbols(Locale.ENGLISH));\r
1100                 f.applyPattern("");\r
1101                 break;\r
1102             }\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
1106             }\r
1107         }\r
1108     }\r
1109 \r
1110 //#if defined(FOUNDATION10)\r
1111 //#else\r
1112     /**\r
1113      * BigDecimal numbers get their fractions truncated by NumberFormat.\r
1114      */\r
1115     public void Test4141750() {\r
1116         try {\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
1121         }\r
1122         catch (Exception e) {\r
1123             warnln(e.toString());\r
1124             //e.printStackTrace();\r
1125         }\r
1126     }\r
1127 //#endif\r
1128 \r
1129     /**\r
1130      * DecimalFormat toPattern() doesn't quote special characters or handle\r
1131      * single quotes.\r
1132      */\r
1133     public void Test4145457() {\r
1134         try {\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
1140 \r
1141             String[] PATS = { "#.00 'num''ber'", "''#.00''" };\r
1142 \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
1148             \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
1153             \r
1154                 if (!pat.equals(pat2))\r
1155                     errln("Fail with \"" + PATS[i] + "\": Patterns should concur, \"" +\r
1156                           pat + "\" vs. \"" + pat2 + "\"");\r
1157                 else\r
1158                     logln("Ok \"" + PATS[i] + "\" toPattern() -> \"" + pat + '"');\r
1159 \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
1164                 }\r
1165                 else {\r
1166                     errln("Fail " + pi + " x \"" + PATS[i] + "\" -> \"" +\r
1167                           out + "\" -> " + val + " -> \"" +\r
1168                           out2 + "\" -> " + val2);\r
1169                 }\r
1170             }\r
1171         }\r
1172         catch (ParseException e) {\r
1173             errln("Fail: " + e);\r
1174             e.printStackTrace();\r
1175         }\r
1176     }\r
1177 \r
1178     /**\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
1182      */\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
1193         } else {\r
1194             logln("Test passed");\r
1195             logln(" Minimum integer digits : " + minIntDig);\r
1196         }\r
1197     }\r
1198 \r
1199     /**\r
1200      * DecimalFormat formats -0.0 as +0.0\r
1201      * See also older related bug 4106658, 4106667\r
1202      */\r
1203     public void Test4147706() {\r
1204         DecimalFormat df = new DecimalFormat("#,##0.0##");\r
1205         df.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.ENGLISH));\r
1206         double d1 = -0.0;\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
1212         }\r
1213         if (!f2.toString().equals("-0.0")) {\r
1214             errln(d2 + " x \"" + df.toPattern() + "\" is formatted as \"" + f2 + '"');\r
1215         }\r
1216     }\r
1217 \r
1218     /**\r
1219      * NumberFormat cannot format Double.MAX_VALUE\r
1220      */\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
1228         Number n = null;\r
1229         try {\r
1230             n = f.parse(s);\r
1231         } catch (java.text.ParseException e) {\r
1232             errln("Caught a ParseException:");\r
1233             e.printStackTrace();\r
1234         }\r
1235         logln("The string " + s + " parsed as " + n);\r
1236         if (n.doubleValue() != dbl) {\r
1237             errln("Round trip failure");\r
1238         }\r
1239     }\r
1240 \r
1241     /**\r
1242      * NumberFormat does not parse negative zero.\r
1243      */\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
1248             double d = -0.0;\r
1249             String s = f.format(d);\r
1250             double e = f.parse(s).doubleValue();\r
1251             logln("" +\r
1252                   d + " -> " +\r
1253                   '"' + s + '"' + " -> " +\r
1254               e);\r
1255             if (e != 0.0 || 1.0/e > 0.0) {\r
1256                 logln("Failed to parse negative zero");\r
1257             }\r
1258         }\r
1259     }\r
1260 \r
1261     /**\r
1262      * NumberFormat truncates data\r
1263      */\r
1264     public void Test4167494() throws Exception {\r
1265         NumberFormat fmt = NumberFormat.getInstance(Locale.US);\r
1266         \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
1271         if (match) {\r
1272             logln("" + a + " -> \"" + s + "\" -> " + b + " ok");\r
1273         } else {\r
1274             errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL");\r
1275         }\r
1276 \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
1281         if (false) {\r
1282             a = Double.MIN_VALUE;\r
1283             s = fmt.format(a);\r
1284             b = fmt.parse(s).doubleValue();\r
1285             match = a == b;\r
1286             if (match) {\r
1287                 logln("" + a + " -> \"" + s + "\" -> " + b + " ok");\r
1288             } else {\r
1289                 errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL");\r
1290             }\r
1291         }\r
1292     }\r
1293 \r
1294     /**\r
1295      * DecimalFormat.parse() fails when ParseIntegerOnly set to true\r
1296      */\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
1307         }\r
1308         Locale.setDefault(savedLocale);\r
1309     }\r
1310 \r
1311     /**\r
1312      * toPattern only puts the first grouping separator in.\r
1313      */\r
1314     public void Test4176114() {\r
1315         String[] DATA = {\r
1316             "00", "#00",\r
1317             "000", "#000", // No grouping\r
1318             "#000", "#000", // No grouping\r
1319             "#,##0", "#,##0",\r
1320             "#,000", "#,000",\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
1325         };\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
1331             }\r
1332         }\r
1333     }\r
1334 \r
1335     /**\r
1336      * DecimalFormat is incorrectly rounding numbers like 1.2501 to 1.2\r
1337      */\r
1338     public void Test4179818() {\r
1339         String DATA[] = {\r
1340             // Input  Pattern  Expected output\r
1341             "1.2511", "#.#",   "1.3",\r
1342             "1.2501", "#.#",   "1.3",\r
1343             "0.9999", "#",     "1",\r
1344         };\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
1355             } else {\r
1356                 errln("FAIL: " + in + " x  " + pat + " = " + out +\r
1357                       ", expected " + exp);\r
1358             }\r
1359         }\r
1360     }\r
1361 \r
1362     public void Test4185761() throws IOException, ClassNotFoundException {\r
1363         ByteArrayOutputStream baos = new ByteArrayOutputStream();\r
1364         ObjectOutputStream oos = new ObjectOutputStream(baos);\r
1365         \r
1366         NumberFormat nf = NumberFormat.getInstance(Locale.US);\r
1367 \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
1374         \r
1375         oos.writeObject(nf);\r
1376         oos.flush();\r
1377         baos.close();\r
1378         \r
1379         byte[] bytes = baos.toByteArray();\r
1380 \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
1385     // this class.\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
1392                         offsets[j] = i;\r
1393                         break;\r
1394                     }\r
1395                 }\r
1396             }\r
1397         }\r
1398 \r
1399         {\r
1400             ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));\r
1401             Object o = ois.readObject();\r
1402             ois.close();\r
1403             \r
1404             if (!nf.equals(o)) {\r
1405                 errln("Fail: NumberFormat serialization/equality bug");\r
1406             } else {\r
1407                 logln("NumberFormat serialization/equality is OKAY.");\r
1408             }\r
1409         }\r
1410 \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
1415         }\r
1416 \r
1417         {\r
1418             ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));\r
1419             try {\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
1425             }\r
1426         }\r
1427 \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
1433         }\r
1434 \r
1435         {\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
1446             } else {\r
1447                 logln("Ok: Digit count out of range");\r
1448             }\r
1449         }\r
1450     }\r
1451 \r
1452 \r
1453     /**\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
1457      * 4212073.\r
1458      */\r
1459     public void Test4212072() throws IOException, ClassNotFoundException {\r
1460         DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);\r
1461         DecimalFormat fmt = new DecimalFormat("#", sym);\r
1462 \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
1467                   ", exp ^1");\r
1468         }\r
1469         if (!fmt.getNegativePrefix().equals("^")) {\r
1470             errln("FAIL: (minus=^).getNegativePrefix -> " +\r
1471                   fmt.getNegativePrefix() + ", exp ^");\r
1472         }\r
1473         sym.setMinusSign('-');\r
1474 \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
1480                   ", exp 25^");\r
1481         }\r
1482         if (!fmt.getPositiveSuffix().equals("^")) {\r
1483             errln("FAIL: (percent=^).getPositiveSuffix -> " +\r
1484                   fmt.getPositiveSuffix() + ", exp ^");\r
1485         }\r
1486         sym.setPercent('%');\r
1487         \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
1493                   ", exp 250^");\r
1494         }\r
1495         if (!fmt.getPositiveSuffix().equals("^")) {\r
1496             errln("FAIL: (permill=^).getPositiveSuffix -> " +\r
1497                   fmt.getPositiveSuffix() + ", exp ^");\r
1498         }\r
1499         sym.setPerMill('\u2030');\r
1500 \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
1507         }\r
1508         if (!fmt.getPositivePrefix().equals("usd")) {\r
1509             errln("FAIL: (currency=usd).getPositivePrefix -> " +\r
1510                   fmt.getPositivePrefix() + ", exp usd");\r
1511         }\r
1512         sym.setCurrencySymbol("$");\r
1513 \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
1520         }\r
1521         if (!fmt.getPositivePrefix().equals("DOL")) {\r
1522             errln("FAIL: (intlcurrency=DOL).getPositivePrefix -> " +\r
1523                   fmt.getPositivePrefix() + ", exp DOL");\r
1524         }\r
1525         sym.setInternationalCurrencySymbol("USD");\r
1526 \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
1531             return;\r
1532         }\r
1533         \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
1539                 NumberFormat nf;\r
1540                 switch (j) {\r
1541                 case 0:\r
1542                     nf = NumberFormat.getInstance(avail[i]);\r
1543                     break;\r
1544                 case 1:\r
1545                     nf = NumberFormat.getCurrencyInstance(avail[i]);\r
1546                     break;\r
1547                 default:\r
1548                     nf = NumberFormat.getPercentInstance(avail[i]);\r
1549                     break;\r
1550                 }\r
1551                 DecimalFormat df = (DecimalFormat) nf;\r
1552                 \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
1560                 }\r
1561 \r
1562                 // Test toLocalizedPattern/applyLocalizedPattern round trip\r
1563                 pat = df.toLocalizedPattern();\r
1564                 try{\r
1565                     f2.applyLocalizedPattern(pat);\r
1566                     \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
1572   \r
1573                     }\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
1578                     }\r
1579                    \r
1580                 }catch(IllegalArgumentException ex){\r
1581                     errln(ex.getMessage()+" for locale "+ df.getLocale(ULocale.ACTUAL_LOCALE));\r
1582                 }\r
1583                 \r
1584 \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
1589                 oos.flush();\r
1590                 baos.close();\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
1597                           "\" -> " +\r
1598                           (f2 != null ? ("\""+f2.toPattern()+'"') : "null"));\r
1599                 }\r
1600 \r
1601             }\r
1602         }\r
1603 \r
1604         // @since ICU 2.4\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
1613             try {\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
1618                           pat2 + "\"");\r
1619                 }\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
1624                           exp + "\"");\r
1625                 }\r
1626             } catch (IllegalArgumentException e) {\r
1627                 errln("FAIL: Pattern \"" + pat + "\" => " + e.getMessage());\r
1628             }\r
1629         }\r
1630     }\r
1631 \r
1632     /**\r
1633      * DecimalFormat.parse() fails for mulipliers 2^n.\r
1634      */\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
1645                           ") => " + n);\r
1646                 }\r
1647             }\r
1648         }\r
1649     }\r
1650 \r
1651     /**\r
1652      * DecimalFormat formats 1.001 to "1.00" instead of "1" with 2 fraction\r
1653      * digits.\r
1654      */\r
1655     public void Test4217661() {\r
1656         Object[] DATA = {\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
1661         };\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
1668             }\r
1669         }\r
1670     }\r
1671     \r
1672     /**\r
1673      * 4243011: Formatting .5 rounds to "1" instead of "0"\r
1674      */\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
1678         \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
1684             } else {\r
1685                 errln("FAIL: got " + result);\r
1686             }\r
1687         }\r
1688     }\r
1689     \r
1690     /**\r
1691      * 4243108: format(0.0) gives "0.1" if preceded by parse("99.99")\r
1692      */\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
1698         } else {\r
1699             errln("FAIL: got " + result);\r
1700         }\r
1701         try {\r
1702             double dResult = f.parse("99.99").doubleValue();\r
1703             if (dResult == 99.99) {\r
1704                 logln("OK: got " + dResult);\r
1705             } else {\r
1706                 errln("FAIL: got " + dResult);\r
1707             }\r
1708         } catch (ParseException e) {\r
1709             errln("Caught a ParseException:");\r
1710             e.printStackTrace();\r
1711         }            \r
1712         result = f.format(0.0);\r
1713         if (result.equals("0")) {\r
1714             logln("OK: got " + result);\r
1715         } else {\r
1716             errln("FAIL: got " + result);\r
1717         }\r
1718     }\r
1719     \r
1720     /**\r
1721      * 4330377: DecimalFormat engineering notation gives incorrect results\r
1722      */\r
1723     public void test4330377() {\r
1724         /*\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
1747         };\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
1757                 }\r
1758             }\r
1759         }\r
1760         */\r
1761     }\r
1762     \r
1763     /**\r
1764      * 4233840: NumberFormat does not round correctly\r
1765      */\r
1766     public void test4233840() {\r
1767         float f = 0.0099f;\r
1768 \r
1769         NumberFormat nf = new DecimalFormat("0.##", new DecimalFormatSymbols(Locale.US));\r
1770     nf.setMinimumFractionDigits(2);\r
1771     \r
1772     String result = nf.format(f);\r
1773     \r
1774     if (!result.equals("0.01")) {\r
1775         errln("FAIL: input: " + f + ", expected: 0.01, got: " + result);\r
1776     }\r
1777     }\r
1778     \r
1779     /**\r
1780      * 4241880: Decimal format doesnt round a double properly when the number is less than 1\r
1781      */\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
1790         };\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
1796         };\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
1802         };\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
1811             }\r
1812         }\r
1813         Locale.setDefault(savedLocale);\r
1814     }\r
1815 }\r
1816 \r
1817 class myformat implements Serializable\r
1818 {\r
1819     /**\r
1820      * For serialization\r
1821      */\r
1822     private static final long serialVersionUID = 4120813612616076506L;\r
1823     DateFormat _dateFormat = DateFormat.getDateInstance();\r
1824 \r
1825     public String Now()\r
1826     {\r
1827         GregorianCalendar calendar = new GregorianCalendar();\r
1828         Date t = calendar.getTime();\r
1829         String nowStr = _dateFormat.format(t);\r
1830         return nowStr;\r
1831     }\r
1832 }\r
1833 \r
1834 class MyNumberFormatTest extends NumberFormat {\r
1835     /**\r
1836      * For serialization\r
1837      */\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
1841     }\r
1842     public StringBuffer format(long number,StringBuffer toAppendTo, FieldPosition pos) {\r
1843         return new StringBuffer("");\r
1844     }\r
1845     public Number parse(String text, ParsePosition parsePosition) {\r
1846         return new Integer(0);\r
1847     }\r
1848 //#if defined(FOUNDATION10)\r
1849 //#else\r
1850     public StringBuffer format(java.math.BigDecimal number, StringBuffer toAppendTo, FieldPosition pos) {\r
1851         return new StringBuffer("");\r
1852     }\r
1853 //#endif\r
1854     public StringBuffer format(BigInteger number, StringBuffer toAppendTo, FieldPosition pos) {\r
1855         return new StringBuffer("");\r
1856     }\r
1857     public StringBuffer format(com.ibm.icu.math.BigDecimal number, StringBuffer toAppendTo, FieldPosition pos) {\r
1858         return new StringBuffer("");\r
1859     }\r
1860 }\r
1861 \r