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