]> gitweb.fperrin.net Git - Dictionary.git/blob - jars/icu4j-4_2_1-src/src/com/ibm/icu/dev/test/format/IntlTestDecimalFormatAPI.java
go
[Dictionary.git] / jars / icu4j-4_2_1-src / src / com / ibm / icu / dev / test / format / IntlTestDecimalFormatAPI.java
1 //##header J2SE15
2 /*****************************************************************************************
3  *
4  *   Copyright (C) 1996-2009, International Business Machines
5  *   Corporation and others.  All Rights Reserved.
6  **/
7
8 /** 
9  * Port From:   JDK 1.4b1 : java.text.Format.IntlTestDecimalFormatAPI
10  * Source File: java/text/format/IntlTestDecimalFormatAPI.java
11  **/
12  
13 /*
14     @test 1.4 98/03/06
15     @summary test International Decimal Format API
16 */
17
18 package com.ibm.icu.dev.test.format;
19
20 import com.ibm.icu.text.*;
21 import com.ibm.icu.math.BigDecimal;
22 import com.ibm.icu.math.MathContext;
23 import java.util.Locale;
24 import java.text.ParsePosition;
25 import java.text.Format;
26 import java.text.FieldPosition;
27 import java.text.ParseException;
28 import com.ibm.icu.text.DecimalFormat;
29
30 public class IntlTestDecimalFormatAPI extends com.ibm.icu.dev.test.TestFmwk
31 {
32     public static void main(String[] args)  throws Exception {
33         new IntlTestDecimalFormatAPI().run(args);
34     }
35     
36     /**
37      * Problem 1: simply running 
38      * decF4.setRoundingMode(java.math.BigDecimal.ROUND_HALF_UP) does not work 
39      * as decF4.setRoundingIncrement(.0001) must also be run.
40      * Problem 2: decF4.format(8.88885) does not return 8.8889 as expected. 
41      * You must run decF4.format(new BigDecimal(Double.valueOf(8.88885))) in 
42      * order for this to work as expected.
43      * Problem 3: There seems to be no way to set half up to be the default 
44      * rounding mode.
45      * We solved the problem with the code at the bottom of this page however 
46      * this is not quite general purpose enough to include in icu4j. A static
47      * setDefaultRoundingMode function would solve the problem nicely. Also 
48      * decimal places past 20 are not handled properly. A small ammount of work 
49      * would make bring this up to snuff.
50      */
51     public void testJB1871()
52     {
53         // problem 2
54         double number = 8.88885;
55         String expected = "8.8889";
56         
57         String pat = ",##0.0000";
58         DecimalFormat dec = new DecimalFormat(pat);
59         dec.setRoundingMode(BigDecimal.ROUND_HALF_UP);
60         double roundinginc = 0.0001;
61         dec.setRoundingIncrement(roundinginc);
62         String str = dec.format(number);
63         if (!str.equals(expected)) {
64             errln("Fail: " + number + " x \"" + pat + "\" = \"" +
65                   str + "\", expected \"" + expected + "\"");
66         }   
67
68         pat = ",##0.0001";
69         dec = new DecimalFormat(pat);
70         dec.setRoundingMode(BigDecimal.ROUND_HALF_UP);
71         str = dec.format(number);
72         if (!str.equals(expected)) {
73             errln("Fail: " + number + " x \"" + pat + "\" = \"" +
74                   str + "\", expected \"" + expected + "\"");
75         }  
76         
77         // testing 20 decimal places
78         pat = ",##0.00000000000000000001";
79         dec = new DecimalFormat(pat);
80         BigDecimal bignumber = new BigDecimal("8.888888888888888888885");
81         expected = "8.88888888888888888889";
82         
83         dec.setRoundingMode(BigDecimal.ROUND_HALF_UP);
84         str = dec.format(bignumber); 
85         if (!str.equals(expected)) {
86             errln("Fail: " + bignumber + " x \"" + pat + "\" = \"" +
87                   str + "\", expected \"" + expected + "\"");
88         }   
89         
90     }
91
92     /** 
93      * This test checks various generic API methods in DecimalFormat to achieve 
94      * 100% API coverage.
95      */
96     public void TestAPI()
97     {
98         logln("DecimalFormat API test---"); logln("");
99         Locale.setDefault(Locale.ENGLISH);
100
101         // ======= Test constructors
102
103         logln("Testing DecimalFormat constructors");
104
105         DecimalFormat def = new DecimalFormat();
106
107         final String pattern = new String("#,##0.# FF");
108         DecimalFormat pat = null;
109         try {
110             pat = new DecimalFormat(pattern);
111         }
112         catch (IllegalArgumentException e) {
113             errln("ERROR: Could not create DecimalFormat (pattern)");
114         }
115
116         DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.FRENCH);
117
118         DecimalFormat cust1 = new DecimalFormat(pattern, symbols);
119
120         // ======= Test clone(), assignment, and equality
121
122         logln("Testing clone() and equality operators");
123
124         Format clone = (Format) def.clone();
125         if( ! def.equals(clone)) {
126             errln("ERROR: Clone() failed");
127         }
128
129         // ======= Test various format() methods
130
131         logln("Testing various format() methods");
132
133 //        final double d = -10456.0037; // this appears as -10456.003700000001 on NT
134 //        final double d = -1.04560037e-4; // this appears as -1.0456003700000002E-4 on NT
135         final double d = -10456.00370000000000; // this works!
136         final long l = 100000000;
137         logln("" + d + " is the double value");
138
139         StringBuffer res1 = new StringBuffer();
140         StringBuffer res2 = new StringBuffer();
141         StringBuffer res3 = new StringBuffer();
142         StringBuffer res4 = new StringBuffer();
143         FieldPosition pos1 = new FieldPosition(0);
144         FieldPosition pos2 = new FieldPosition(0);
145         FieldPosition pos3 = new FieldPosition(0);
146         FieldPosition pos4 = new FieldPosition(0);
147
148         res1 = def.format(d, res1, pos1);
149         logln("" + d + " formatted to " + res1);
150
151         res2 = pat.format(l, res2, pos2);
152         logln("" + l + " formatted to " + res2);
153
154         res3 = cust1.format(d, res3, pos3);
155         logln("" + d + " formatted to " + res3);
156
157         res4 = cust1.format(l, res4, pos4);
158         logln("" + l + " formatted to " + res4);
159
160         // ======= Test parse()
161
162         logln("Testing parse()");
163
164         String text = new String("-10,456.0037");
165         ParsePosition pos = new ParsePosition(0);
166         String patt = new String("#,##0.#");
167         pat.applyPattern(patt);
168         double d2 = pat.parse(text, pos).doubleValue();
169         if(d2 != d) {
170             errln("ERROR: Roundtrip failed (via parse(" + d2 + " != " + d + ")) for " + text);
171         }
172         logln(text + " parsed into " + (long) d2);
173
174         // ======= Test getters and setters
175
176         logln("Testing getters and setters");
177
178         final DecimalFormatSymbols syms = pat.getDecimalFormatSymbols();
179         def.setDecimalFormatSymbols(syms);
180         if( ! pat.getDecimalFormatSymbols().equals(def.getDecimalFormatSymbols())) {
181             errln("ERROR: set DecimalFormatSymbols() failed");
182         }
183
184         String posPrefix;
185         pat.setPositivePrefix("+");
186         posPrefix = pat.getPositivePrefix();
187         logln("Positive prefix (should be +): " + posPrefix);
188         if(posPrefix != "+") {
189             errln("ERROR: setPositivePrefix() failed");
190         }
191
192         String negPrefix;
193         pat.setNegativePrefix("-");
194         negPrefix = pat.getNegativePrefix();
195         logln("Negative prefix (should be -): " + negPrefix);
196         if(negPrefix != "-") {
197             errln("ERROR: setNegativePrefix() failed");
198         }
199
200         String posSuffix;
201         pat.setPositiveSuffix("_");
202         posSuffix = pat.getPositiveSuffix();
203         logln("Positive suffix (should be _): " + posSuffix);
204         if(posSuffix != "_") {
205             errln("ERROR: setPositiveSuffix() failed");
206         }
207
208         String negSuffix;
209         pat.setNegativeSuffix("~");
210         negSuffix = pat.getNegativeSuffix();
211         logln("Negative suffix (should be ~): " + negSuffix);
212         if(negSuffix != "~") {
213             errln("ERROR: setNegativeSuffix() failed");
214         }
215
216         long multiplier = 0;
217         pat.setMultiplier(8);
218         multiplier = pat.getMultiplier();
219         logln("Multiplier (should be 8): " + multiplier);
220         if(multiplier != 8) {
221             errln("ERROR: setMultiplier() failed");
222         }
223
224         int groupingSize = 0;
225         pat.setGroupingSize(2);
226         groupingSize = pat.getGroupingSize();
227         logln("Grouping size (should be 2): " + (long) groupingSize);
228         if(groupingSize != 2) {
229             errln("ERROR: setGroupingSize() failed");
230         }
231
232         pat.setDecimalSeparatorAlwaysShown(true);
233         boolean tf = pat.isDecimalSeparatorAlwaysShown();
234         logln("DecimalSeparatorIsAlwaysShown (should be true) is " +  (tf ? "true" : "false"));
235         if(tf != true) {
236             errln("ERROR: setDecimalSeparatorAlwaysShown() failed");
237         }
238
239         String funkyPat;
240         funkyPat = pat.toPattern();
241         logln("Pattern is " + funkyPat);
242
243         String locPat;
244         locPat = pat.toLocalizedPattern();
245         logln("Localized pattern is " + locPat);
246
247         // ======= Test applyPattern()
248
249         logln("Testing applyPattern()");
250
251         String p1 = new String("#,##0.0#;(#,##0.0#)");
252         logln("Applying pattern " + p1);
253         pat.applyPattern(p1);
254         String s2;
255         s2 = pat.toPattern();
256         logln("Extracted pattern is " + s2);
257         if( ! s2.equals(p1) ) {
258             errln("ERROR: toPattern() result did not match pattern applied");
259         }
260
261         String p2 = new String("#,##0.0# FF;(#,##0.0# FF)");
262         logln("Applying pattern " + p2);
263         pat.applyLocalizedPattern(p2);
264         String s3;
265         s3 = pat.toLocalizedPattern();
266         logln("Extracted pattern is " + s3);
267         if( ! s3.equals(p2) ) {
268             errln("ERROR: toLocalizedPattern() result did not match pattern applied");
269         }
270     }
271
272 //#if defined(FOUNDATION10) || defined(J2SE13)
273 //#else
274     public void testJB6134()
275     {
276         DecimalFormat decfmt = new DecimalFormat();
277         StringBuffer buf = new StringBuffer();
278
279         FieldPosition fposByInt = new FieldPosition(NumberFormat.INTEGER_FIELD);
280         decfmt.format(123, buf, fposByInt);
281
282         buf.setLength(0);
283         FieldPosition fposByField = new FieldPosition(NumberFormat.Field.INTEGER);
284         decfmt.format(123, buf, fposByField);
285
286         if (fposByInt.getEndIndex() != fposByField.getEndIndex())
287         {
288             errln("ERROR: End index for integer field - fposByInt:" + fposByInt.getEndIndex() +
289                 " / fposByField: " + fposByField.getEndIndex());
290         }
291     }
292 //#endif
293
294     public void testJB4971()
295     {
296         DecimalFormat decfmt = new DecimalFormat();
297         MathContext resultICU;
298
299         MathContext comp1 = new MathContext(0, MathContext.PLAIN);
300         resultICU = decfmt.getMathContextICU();
301         if ((comp1.getDigits() != resultICU.getDigits()) ||
302             (comp1.getForm() != resultICU.getForm()) ||
303             (comp1.getLostDigits() != resultICU.getLostDigits()) ||
304             (comp1.getRoundingMode() != resultICU.getRoundingMode()))
305         {
306             errln("ERROR: Math context 1 not equal - result: " + resultICU.toString() +
307                 " / expected: " + comp1.toString());
308         }
309
310         MathContext comp2 = new MathContext(5, MathContext.ENGINEERING);
311         decfmt.setMathContextICU(comp2);
312         resultICU = decfmt.getMathContextICU();
313         if ((comp2.getDigits() != resultICU.getDigits()) ||
314             (comp2.getForm() != resultICU.getForm()) ||
315             (comp2.getLostDigits() != resultICU.getLostDigits()) ||
316             (comp2.getRoundingMode() != resultICU.getRoundingMode()))
317         {
318             errln("ERROR: Math context 2 not equal - result: " + resultICU.toString() +
319                 " / expected: " + comp2.toString());
320         }
321
322 //#if defined(FOUNDATION10) || defined(J2SE13) || defined(J2SE14)
323 //#else
324
325         java.math.MathContext result;
326
327         java.math.MathContext comp3 = new java.math.MathContext(3, java.math.RoundingMode.DOWN);
328         decfmt.setMathContext(comp3);
329         result = decfmt.getMathContext();
330         if ((comp3.getPrecision() != result.getPrecision()) ||
331             (comp3.getRoundingMode() != result.getRoundingMode()))
332         {
333             errln("ERROR: Math context 3 not equal - result: " + result.toString() +
334                 " / expected: " + comp3.toString());
335         }
336
337 //#endif
338
339     }
340
341     public void testJB6354()
342     {
343         DecimalFormat pat = new DecimalFormat("#,##0.00");
344
345         // get default rounding increment
346 //#if defined(FOUNDATION10)
347 //##        com.ibm.icu.math.BigDecimal r1 = pat.getRoundingIncrement();
348 //#else
349         java.math.BigDecimal r1 = pat.getRoundingIncrement();
350 //#endif
351
352         // set rounding mode with zero increment.  Rounding 
353         // increment should be set by this operation
354         pat.setRoundingMode(BigDecimal.ROUND_UP);
355 //#if defined(FOUNDATION10)
356 //##        com.ibm.icu.math.BigDecimal r2 = pat.getRoundingIncrement();
357 //#else
358         java.math.BigDecimal r2 = pat.getRoundingIncrement();
359 //#endif
360
361         // check for different values
362         if ((r1 != null) && (r2 != null))
363         {
364             if (r1.compareTo(r2) == 0)
365             {
366                 errln("ERROR: Rounding increment did not change");
367             }
368         }
369     }
370     
371     public void testJB6648()
372     {
373         DecimalFormat df = new DecimalFormat();
374         df.setParseStrict(true);
375         
376         String numstr = new String();
377         
378         String[] patterns = {
379             "0",
380             "00",
381             "000",
382             "0,000",
383             "0.0",
384             "#000.0"          
385         };
386         
387         for(int i=0; i < patterns.length; i++) {
388             df.applyPattern(patterns[i]);
389             numstr = df.format(5);        
390             try {
391                 Number n = df.parse(numstr);
392                 logln("INFO: Parsed " + numstr + " -> " + n);
393             } catch (ParseException pe) {
394                 errln("ERROR: Failed round trip with strict parsing.");
395             }           
396         }
397         
398         df.applyPattern(patterns[1]);
399         numstr = "005";        
400         try {
401             Number n = df.parse(numstr);
402             errln("ERROR: Expected round trip failure not encountered: numstr -> " + n);
403         } catch (ParseException pe) {
404             logln("INFO: Expected ParseExpection for " + numstr + " with strick parse enabled");
405         }  
406         
407     }
408 }