Source Code Cross Referenced for NumberRegression.java in  » Internationalization-Localization » icu4j » com » ibm » icu » dev » test » format » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Internationalization Localization » icu4j » com.ibm.icu.dev.test.format 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        //##header
0002:        /*****************************************************************************************
0003:         *
0004:         * Copyright (C) 1996-2006, International Business Machines
0005:         * Corporation and others.  All Rights Reserved.
0006:         **/
0007:
0008:        /** 
0009:         * Port From:   JDK 1.4b1 : java.text.Format.NumberRegression
0010:         * Source File: java/text/format/NumberRegression.java
0011:         **/
0012:
0013:        /**
0014:         * @test 1.49 01/05/21
0015:         * @bug 4052223 4059870 4061302 4062486 4066646 4068693 4070798 4071005 4071014
0016:         * 4071492 4071859 4074454 4074620 4075713 4083018 4086575 4087244 4087245
0017:         * 4087251 4087535 4088161 4088503 4090489 4090504 4092480 4092561 4095713
0018:         * 4098741 4099404 4101481 4106658 4106662 4106664 4108738 4110936 4122840
0019:         * 4125885 4134034 4134300 4140009 4141750 4145457 4147295 4147706 4162198
0020:         * 4162852 4167494 4170798 4176114 4179818 4185761 4212072 4212073 4216742
0021:         * 4217661 4243011 4243108 4330377 4233840
0022:         * @summary Regression tests for NumberFormat and associated classes
0023:         */package com.ibm.icu.dev.test.format;
0024:
0025:        //import com.ibm.icu.impl.ICULocaleData;
0026:        import com.ibm.icu.impl.ICUResourceBundle;
0027:        import com.ibm.icu.text.*;
0028:        import com.ibm.icu.util.*;
0029:
0030:        import java.io.*;
0031:        import java.math.BigDecimal;
0032:        import java.math.BigInteger;
0033:        import java.text.FieldPosition;
0034:        import java.text.ParseException;
0035:        import java.text.ParsePosition;
0036:        import java.util.Date;
0037:        import java.util.Locale;
0038:
0039:        public class NumberRegression extends com.ibm.icu.dev.test.TestFmwk {
0040:
0041:            public static void main(String[] args) throws Exception {
0042:                new NumberRegression().run(args);
0043:            }
0044:
0045:            private static final char EURO = '\u20ac';
0046:
0047:            /**
0048:             * NumberFormat.equals comparing with null should always return false.
0049:             */
0050:            public void Test4075713() {
0051:
0052:                try {
0053:                    MyNumberFormatTest tmp = new MyNumberFormatTest();
0054:                    if (!tmp.equals(null))
0055:                        logln("NumberFormat.equals passed");
0056:                } catch (NullPointerException e) {
0057:                    errln("(new MyNumberFormatTest()).equals(null) throws unexpected exception");
0058:                }
0059:            }
0060:
0061:            /**
0062:             * NumberFormat.equals comparing two obj equal even the setGroupingUsed
0063:             * flag is different.
0064:             */
0065:            public void Test4074620() {
0066:
0067:                MyNumberFormatTest nf1 = new MyNumberFormatTest();
0068:                MyNumberFormatTest nf2 = new MyNumberFormatTest();
0069:
0070:                nf1.setGroupingUsed(false);
0071:                nf2.setGroupingUsed(true);
0072:
0073:                if (nf1.equals(nf2))
0074:                    errln("Test for bug 4074620 failed");
0075:                else
0076:                    logln("Test for bug 4074620 passed.");
0077:                return;
0078:            }
0079:
0080:            /**
0081:             * DecimalFormat.format() incorrectly uses maxFractionDigits setting.
0082:             */
0083:
0084:            public void Test4088161() {
0085:                DecimalFormat df = new DecimalFormat();
0086:                double d = 100;
0087:                df.setMinimumFractionDigits(0);
0088:                df.setMaximumFractionDigits(16);
0089:                StringBuffer sBuf1 = new StringBuffer("");
0090:                FieldPosition fp1 = new FieldPosition(0);
0091:                logln("d = " + d);
0092:                logln("maxFractionDigits = " + df.getMaximumFractionDigits());
0093:                logln(" format(d) = '" + df.format(d, sBuf1, fp1) + "'");
0094:                df.setMaximumFractionDigits(17);
0095:                StringBuffer sBuf2 = new StringBuffer("");
0096:                FieldPosition fp2 = new FieldPosition(0);
0097:                logln("maxFractionDigits = " + df.getMaximumFractionDigits());
0098:                df.format(d, sBuf2, fp2);
0099:                if (!sBuf2.toString().equals("100"))
0100:                    errln(" format(d) = '" + sBuf2 + "'");
0101:            }
0102:
0103:            /**
0104:             * DecimalFormatSymbols should be cloned in the ctor DecimalFormat.
0105:             * DecimalFormat(String, DecimalFormatSymbols).
0106:             */
0107:            public void Test4087245() {
0108:                DecimalFormatSymbols symbols = new DecimalFormatSymbols();
0109:                DecimalFormat df = new DecimalFormat("#,##0.0", symbols);
0110:                long n = 123;
0111:                StringBuffer buf1 = new StringBuffer();
0112:                StringBuffer buf2 = new StringBuffer();
0113:                logln("format(" + n + ") = "
0114:                        + df.format(n, buf1, new FieldPosition(0)));
0115:                symbols.setDecimalSeparator('p'); // change value of field
0116:                logln("format(" + n + ") = "
0117:                        + df.format(n, buf2, new FieldPosition(0)));
0118:                if (!buf1.toString().equals(buf2.toString()))
0119:                    errln("Test for bug 4087245 failed");
0120:            }
0121:
0122:            /**
0123:             * DecimalFormat.format() incorrectly formats 0.0
0124:             */
0125:            public void Test4087535() {
0126:                DecimalFormat df = new DecimalFormat();
0127:                df.setMinimumIntegerDigits(0);
0128:
0129:                double n = 0;
0130:                String buffer = new String();
0131:                buffer = df.format(n);
0132:                if (buffer.length() == 0)
0133:                    errln(n + ": '" + buffer + "'");
0134:                n = 0.1;
0135:                buffer = df.format(n);
0136:                if (buffer.length() == 0)
0137:                    errln(n + ": '" + buffer + "'");
0138:            }
0139:
0140:            /**
0141:             * DecimalFormat.format fails when groupingSize is set to 0.
0142:             */
0143:            public void Test4088503() {
0144:                DecimalFormat df = new DecimalFormat();
0145:                df.setGroupingSize(0);
0146:                StringBuffer sBuf = new StringBuffer("");
0147:                FieldPosition fp = new FieldPosition(0);
0148:                try {
0149:                    logln(df.format(123, sBuf, fp).toString());
0150:                } catch (Exception foo) {
0151:                    errln("Test for bug 4088503 failed.");
0152:                }
0153:
0154:            }
0155:
0156:            /**
0157:             * NumberFormat.getCurrencyInstance is wrong.
0158:             */
0159:            public void Test4066646() {
0160:                //float returnfloat = 0.0f; //The variable is never used
0161:                assignFloatValue(2.04f);
0162:                assignFloatValue(2.03f);
0163:                assignFloatValue(2.02f);
0164:                assignFloatValue(0.0f);
0165:            }
0166:
0167:            public float assignFloatValue(float returnfloat) {
0168:                logln(" VALUE " + returnfloat);
0169:                NumberFormat nfcommon = NumberFormat
0170:                        .getCurrencyInstance(Locale.US);
0171:                nfcommon.setGroupingUsed(false);
0172:
0173:                String stringValue = nfcommon.format(returnfloat).substring(1);
0174:                if (Float.valueOf(stringValue).floatValue() != returnfloat)
0175:                    errln(" DISPLAYVALUE " + stringValue);
0176:                return returnfloat;
0177:            } // End Of assignFloatValue()
0178:
0179:            /**
0180:             * DecimalFormat throws exception when parsing "0"
0181:             */
0182:            public void Test4059870() {
0183:                DecimalFormat format = new DecimalFormat("00");
0184:                try {
0185:                    logln(format.parse("0").toString());
0186:                } catch (Exception e) {
0187:                    errln("Test for bug 4059870 failed : " + e);
0188:                }
0189:            }
0190:
0191:            /**
0192:             * DecimalFormatSymbol.equals should always return false when
0193:             * comparing with null.
0194:             */
0195:
0196:            public void Test4083018() {
0197:                DecimalFormatSymbols dfs = new DecimalFormatSymbols();
0198:                try {
0199:                    if (!dfs.equals(null))
0200:                        logln("Test Passed!");
0201:                } catch (Exception foo) {
0202:                    errln("Test for bug 4083018 failed => Message : "
0203:                            + foo.getMessage());
0204:                }
0205:            }
0206:
0207:            /**
0208:             * DecimalFormat does not round up correctly.
0209:             */
0210:            public void Test4071492() {
0211:                double x = 0.00159999;
0212:                NumberFormat nf = NumberFormat.getInstance();
0213:                nf.setMaximumFractionDigits(4);
0214:                String out = nf.format(x);
0215:                logln("0.00159999 formats with 4 fractional digits to " + out);
0216:                String expected = "0.0016";
0217:                if (!out.equals(expected))
0218:                    errln("FAIL: Expected " + expected);
0219:            }
0220:
0221:            /**
0222:             * A space as a group separator for localized pattern causes
0223:             * wrong format.  WorkAround : use non-breaking space.
0224:             */
0225:            public void Test4086575() {
0226:
0227:                NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE);
0228:                logln("nf toPattern1: " + ((DecimalFormat) nf).toPattern());
0229:                logln("nf toLocPattern1: "
0230:                        + ((DecimalFormat) nf).toLocalizedPattern());
0231:
0232:                // No group separator
0233:                logln("...applyLocalizedPattern ###,00;(###,00) ");
0234:                ((DecimalFormat) nf).applyLocalizedPattern("###,00;(###,00)");
0235:                logln("nf toPattern2: " + ((DecimalFormat) nf).toPattern());
0236:                logln("nf toLocPattern2: "
0237:                        + ((DecimalFormat) nf).toLocalizedPattern());
0238:
0239:                logln("nf: " + nf.format(1234)); // 1234,00
0240:                logln("nf: " + nf.format(-1234)); // (1234,00)
0241:
0242:                // Space as group separator
0243:
0244:                logln("...applyLocalizedPattern # ###,00;(# ###,00) ");
0245:                ((DecimalFormat) nf)
0246:                        .applyLocalizedPattern("#\u00a0###,00;(#\u00a0###,00)");
0247:                logln("nf toPattern2: " + ((DecimalFormat) nf).toPattern());
0248:                logln("nf toLocPattern2: "
0249:                        + ((DecimalFormat) nf).toLocalizedPattern());
0250:                String buffer = nf.format(1234);
0251:                if (!buffer.equals("1\u00a0234,00"))
0252:                    errln("nf : " + buffer); // Expect 1 234,00
0253:                buffer = nf.format(-1234);
0254:                if (!buffer.equals("(1\u00a0234,00)"))
0255:                    errln("nf : " + buffer); // Expect (1 234,00)
0256:
0257:                // Erroneously prints:
0258:                // 1234,00 ,
0259:                // (1234,00 ,)
0260:
0261:            }
0262:
0263:            /**
0264:             * DecimalFormat.parse returns wrong value
0265:             */
0266:            public void Test4068693() {
0267:                logln("----- Test Application -----");
0268:                //ParsePosition pos;
0269:                DecimalFormat df = new DecimalFormat();
0270:                Number d = df.parse("123.55456", new ParsePosition(0));
0271:                if (!d.toString().equals("123.55456")) {
0272:                    errln("Result -> " + d.doubleValue());
0273:                }
0274:            }
0275:
0276:            /* bugs 4069754, 4067878
0277:             * null pointer thrown when accessing a deserialized DecimalFormat
0278:             * object.
0279:             */
0280:            public void Test4069754() throws Exception {
0281:                //try {
0282:                ByteArrayOutputStream baos = new ByteArrayOutputStream();
0283:                ObjectOutputStream oos = new ObjectOutputStream(baos);
0284:                myformat it = new myformat();
0285:                logln(it.Now());
0286:                oos.writeObject(it);
0287:                oos.flush();
0288:                baos.close();
0289:                logln("Save OK!");
0290:                byte[] bytes = baos.toByteArray();
0291:                ObjectInputStream ois = new ObjectInputStream(
0292:                        new ByteArrayInputStream(bytes));
0293:                myformat o = (myformat) ois.readObject();
0294:                ois.close();
0295:                it.Now();
0296:                logln("Load OK!");
0297:                if (!o._dateFormat.equals(it._dateFormat)) {
0298:                    throw new Exception(
0299:                            "The saved and loaded object are not equals!");
0300:                }
0301:                logln("Compare OK!");
0302:                //} catch (Exception foo) {
0303:                //errln("Test for bug 4069754 or 4057878 failed => Exception: " + foo.getMessage());
0304:                //}
0305:            }
0306:
0307:            /**
0308:             * DecimalFormat.applyPattern(String) allows illegal patterns
0309:             */
0310:            public void Test4087251() {
0311:                DecimalFormat df = new DecimalFormat();
0312:                try {
0313:                    df.applyPattern("#.#.#");
0314:                    logln("toPattern() returns \"" + df.toPattern() + "\"");
0315:                    errln("applyPattern(\"#.#.#\") doesn't throw IllegalArgumentException");
0316:                } catch (IllegalArgumentException e) {
0317:                    logln("Caught Illegal Argument Error !");
0318:                }
0319:                // Second test; added 5/11/98 when reported to fail on 1.2b3
0320:                try {
0321:                    df.applyPattern("#0.0#0#0");
0322:                    logln("toPattern() returns \"" + df.toPattern() + "\"");
0323:                    errln("applyPattern(\"#0.0#0#0\") doesn't throw IllegalArgumentException");
0324:                } catch (IllegalArgumentException e) {
0325:                    logln("Ok - IllegalArgumentException for #0.0#0#0");
0326:                }
0327:            }
0328:
0329:            /**
0330:             * DecimalFormat.format() loses precision
0331:             */
0332:            public void Test4090489() {
0333:                DecimalFormat df = new DecimalFormat();
0334:                df.setMinimumFractionDigits(10);
0335:                df.setGroupingUsed(false);
0336:                double d = 1.000000000000001E7;
0337:                BigDecimal bd = new BigDecimal(d);
0338:                StringBuffer sb = new StringBuffer("");
0339:                FieldPosition fp = new FieldPosition(0);
0340:                logln("d = " + d);
0341:                logln("BigDecimal.toString():  " + bd.toString());
0342:                df.format(d, sb, fp);
0343:                if (!sb.toString().equals("10000000.0000000100")) {
0344:                    errln("DecimalFormat.format(): " + sb.toString());
0345:                }
0346:            }
0347:
0348:            /**
0349:             * DecimalFormat.format() loses precision
0350:             */
0351:            public void Test4090504() {
0352:                double d = 1;
0353:                logln("d = " + d);
0354:                DecimalFormat df = new DecimalFormat();
0355:                StringBuffer sb;
0356:                FieldPosition fp;
0357:                try {
0358:                    for (int i = 17; i <= 20; i++) {
0359:                        df.setMaximumFractionDigits(i);
0360:                        sb = new StringBuffer("");
0361:                        fp = new FieldPosition(0);
0362:                        logln("  getMaximumFractionDigits() = " + i);
0363:                        logln("  formated: " + df.format(d, sb, fp));
0364:                    }
0365:                } catch (Exception foo) {
0366:                    errln("Bug 4090504 regression test failed. Message : "
0367:                            + foo.getMessage());
0368:                }
0369:            }
0370:
0371:            /**
0372:             * DecimalFormat.parse(String str, ParsePosition pp) loses precision
0373:             */
0374:            public void Test4095713() {
0375:                DecimalFormat df = new DecimalFormat();
0376:                String str = "0.1234";
0377:                Double d1 = new Double(str);
0378:                Number d2 = df.parse(str, new ParsePosition(0));
0379:                logln(d1.toString());
0380:                if (d2.doubleValue() != d1.doubleValue())
0381:                    errln("Bug 4095713 test failed, new double value : "
0382:                            + d2.doubleValue());
0383:            }
0384:
0385:            /**
0386:             * DecimalFormat.parse() fails when multiplier is not set to 1
0387:             */
0388:            public void Test4092561() {
0389:                Locale savedLocale = Locale.getDefault();
0390:                Locale.setDefault(Locale.US);
0391:                DecimalFormat df = new DecimalFormat();
0392:                String str = Long.toString(Long.MIN_VALUE);
0393:                logln("Long.MIN_VALUE : "
0394:                        + df.parse(str, new ParsePosition(0)).toString());
0395:                df.setMultiplier(100);
0396:                Number num = df.parse(str, new ParsePosition(0));
0397:                if (num.doubleValue() != -9.223372036854776E16) {
0398:                    errln("Bug 4092561 test failed when multiplier is set to not 1.");
0399:                }
0400:                Locale.setDefault(savedLocale);
0401:            }
0402:
0403:            /**
0404:             * DecimalFormat: Negative format ignored.
0405:             */
0406:            public void Test4092480() {
0407:                DecimalFormat dfFoo = new DecimalFormat("000");
0408:
0409:                try {
0410:                    dfFoo.applyPattern("0000;-000");
0411:                    if (!dfFoo.toPattern().equals("#0000"))
0412:                        errln("dfFoo.toPattern : " + dfFoo.toPattern());
0413:                    logln(dfFoo.format(42));
0414:                    logln(dfFoo.format(-42));
0415:                    dfFoo.applyPattern("000;-000");
0416:                    if (!dfFoo.toPattern().equals("#000"))
0417:                        errln("dfFoo.toPattern : " + dfFoo.toPattern());
0418:                    logln(dfFoo.format(42));
0419:                    logln(dfFoo.format(-42));
0420:
0421:                    dfFoo.applyPattern("000;-0000");
0422:                    if (!dfFoo.toPattern().equals("#000"))
0423:                        errln("dfFoo.toPattern : " + dfFoo.toPattern());
0424:                    logln(dfFoo.format(42));
0425:                    logln(dfFoo.format(-42));
0426:
0427:                    dfFoo.applyPattern("0000;-000");
0428:                    if (!dfFoo.toPattern().equals("#0000"))
0429:                        errln("dfFoo.toPattern : " + dfFoo.toPattern());
0430:                    logln(dfFoo.format(42));
0431:                    logln(dfFoo.format(-42));
0432:                } catch (Exception foo) {
0433:                    errln("Message " + foo.getMessage());
0434:                }
0435:            }
0436:
0437:            /**
0438:             * NumberFormat.getCurrencyInstance() produces format that uses
0439:             * decimal separator instead of monetary decimal separator.
0440:             *
0441:             * Rewrote this test not to depend on the actual pattern.  Pattern should
0442:             * never contain the monetary separator!  Decimal separator in pattern is
0443:             * interpreted as monetary separator if currency symbol is seen!
0444:             */
0445:            public void Test4087244() {
0446:                Locale de = new Locale("pt", "PT");
0447:                DecimalFormat df = (DecimalFormat) NumberFormat
0448:                        .getCurrencyInstance(de);
0449:                DecimalFormatSymbols sym = df.getDecimalFormatSymbols();
0450:                sym.setMonetaryDecimalSeparator('$');
0451:                df.setDecimalFormatSymbols(sym);
0452:                char decSep = sym.getDecimalSeparator();
0453:                char monSep = sym.getMonetaryDecimalSeparator();
0454:                //char zero = sym.getZeroDigit(); //The variable is never used
0455:                if (decSep == monSep) {
0456:                    errln("ERROR in test: want decimal sep != monetary sep");
0457:                } else {
0458:                    df.setMinimumIntegerDigits(1);
0459:                    df.setMinimumFractionDigits(2);
0460:                    String str = df.format(1.23);
0461:                    String monStr = "1" + monSep + "23";
0462:                    String decStr = "1" + decSep + "23";
0463:                    if (str.indexOf(monStr) >= 0 && str.indexOf(decStr) < 0) {
0464:                        logln("OK: 1.23 -> \"" + str + "\" contains \""
0465:                                + monStr + "\" and not \"" + decStr + '"');
0466:                    } else {
0467:                        errln("FAIL: 1.23 -> \"" + str
0468:                                + "\", should contain \"" + monStr
0469:                                + "\" and not \"" + decStr + '"');
0470:                    }
0471:                }
0472:            }
0473:
0474:            /**
0475:             * Number format data rounding errors for locale FR
0476:             */
0477:            public void Test4070798() {
0478:                NumberFormat formatter;
0479:                String tempString;
0480:                /* User error :
0481:                String expectedDefault = "-5\u00a0789,987";
0482:                String expectedCurrency = "5\u00a0789,98 F";
0483:                String expectedPercent = "-578\u00a0998%";
0484:                 */
0485:                String expectedDefault = "-5\u00a0789,988";
0486:                String expectedCurrency = "5\u00a0789,99 " + EURO; // euro
0487:                String expectedPercent = "-578\u00a0999\u00a0%";
0488:
0489:                formatter = NumberFormat.getNumberInstance(Locale.FRANCE);
0490:                tempString = formatter.format(-5789.9876);
0491:
0492:                if (tempString.equals(expectedDefault)) {
0493:                    logln("Bug 4070798 default test passed.");
0494:                } else {
0495:                    errln("Failed:" + " Expected " + expectedDefault
0496:                            + " Received " + tempString);
0497:                }
0498:
0499:                formatter = NumberFormat.getCurrencyInstance(Locale.FRANCE);
0500:                tempString = formatter.format(5789.9876);
0501:
0502:                if (tempString.equals(expectedCurrency)) {
0503:                    logln("Bug 4070798 currency test assed.");
0504:                } else {
0505:                    errln("Failed:" + " Expected " + expectedCurrency
0506:                            + " Received " + tempString);
0507:                }
0508:
0509:                formatter = NumberFormat.getPercentInstance(Locale.FRANCE);
0510:                tempString = formatter.format(-5789.9876);
0511:
0512:                if (tempString.equals(expectedPercent)) {
0513:                    logln("Bug 4070798 percentage test passed.");
0514:                } else {
0515:                    errln("Failed:" + " Expected " + expectedPercent
0516:                            + " Received " + tempString);
0517:                }
0518:            }
0519:
0520:            /**
0521:             * Data rounding errors for French (Canada) locale
0522:             */
0523:            public void Test4071005() {
0524:
0525:                NumberFormat formatter;
0526:                String tempString;
0527:                /* user error :
0528:                    String expectedDefault = "-5 789,987";
0529:                    String expectedCurrency = "5 789,98 $";
0530:                    String expectedPercent = "-578 998%";
0531:                 */
0532:                String expectedDefault = "-5\u00a0789,988";
0533:                String expectedCurrency = "5\u00a0789,99 $";
0534:                String expectedPercent = "-578\u00a0999\u00A0%";
0535:
0536:                formatter = NumberFormat
0537:                        .getNumberInstance(Locale.CANADA_FRENCH);
0538:                tempString = formatter.format(-5789.9876);
0539:                if (tempString.equals(expectedDefault)) {
0540:                    logln("Bug 4071005 default test passed.");
0541:                } else {
0542:                    errln("Failed:" + " Expected " + expectedDefault
0543:                            + " Received " + tempString);
0544:                }
0545:
0546:                formatter = NumberFormat
0547:                        .getCurrencyInstance(Locale.CANADA_FRENCH);
0548:                tempString = formatter.format(5789.9876);
0549:
0550:                if (tempString.equals(expectedCurrency)) {
0551:                    logln("Bug 4071005 currency test passed.");
0552:                } else {
0553:                    errln("Failed:" + " Expected " + expectedCurrency
0554:                            + " Received " + tempString);
0555:                }
0556:                formatter = NumberFormat
0557:                        .getPercentInstance(Locale.CANADA_FRENCH);
0558:                tempString = formatter.format(-5789.9876);
0559:
0560:                if (tempString.equals(expectedPercent)) {
0561:                    logln("Bug 4071005 percentage test passed.");
0562:                } else {
0563:                    errln("Failed:" + " Expected " + expectedPercent
0564:                            + " Received " + tempString);
0565:                }
0566:            }
0567:
0568:            /**
0569:             * Data rounding errors for German (Germany) locale
0570:             */
0571:            public void Test4071014() {
0572:                NumberFormat formatter;
0573:                String tempString;
0574:                /* user error :
0575:                String expectedDefault = "-5.789,987";
0576:                String expectedCurrency = "5.789,98 DM";
0577:                String expectedPercent = "-578.998%";
0578:                 */
0579:                String expectedDefault = "-5.789,988";
0580:                String expectedCurrency = "5.789,99 " + EURO;
0581:                String expectedPercent = "-578.999%";
0582:
0583:                formatter = NumberFormat.getNumberInstance(Locale.GERMANY);
0584:                tempString = formatter.format(-5789.9876);
0585:
0586:                if (tempString.equals(expectedDefault)) {
0587:                    logln("Bug 4071014 default test passed.");
0588:                } else {
0589:                    errln("Failed:" + " Expected " + expectedDefault
0590:                            + " Received " + tempString);
0591:                }
0592:
0593:                formatter = NumberFormat.getCurrencyInstance(Locale.GERMANY);
0594:                tempString = formatter.format(5789.9876);
0595:
0596:                if (tempString.equals(expectedCurrency)) {
0597:                    logln("Bug 4071014 currency test passed.");
0598:                } else {
0599:                    errln("Failed:" + " Expected " + expectedCurrency
0600:                            + " Received " + tempString);
0601:                }
0602:
0603:                formatter = NumberFormat.getPercentInstance(Locale.GERMANY);
0604:                tempString = formatter.format(-5789.9876);
0605:
0606:                if (tempString.equals(expectedPercent)) {
0607:                    logln("Bug 4071014 percentage test passed.");
0608:                } else {
0609:                    errln("Failed:" + " Expected " + expectedPercent
0610:                            + " Received " + tempString);
0611:                }
0612:
0613:            }
0614:
0615:            /**
0616:             * Data rounding errors for Italian locale number formats
0617:             * Note- with the Euro, there is no need for currency rounding anymore
0618:             */
0619:            public void Test4071859() {
0620:                NumberFormat formatter;
0621:                String tempString;
0622:                /* user error :
0623:                String expectedDefault = "-5.789,987";
0624:                String expectedCurrency = "-L. 5.789,98";
0625:                String expectedPercent = "-578.998%";
0626:                 */
0627:                String expectedDefault = "-5.789,988";
0628:                String expectedCurrency = "-" + EURO + " 5.789,99";
0629:                String expectedPercent = "-578.999%";
0630:
0631:                formatter = NumberFormat.getNumberInstance(Locale.ITALY);
0632:                tempString = formatter.format(-5789.9876);
0633:
0634:                if (tempString.equals(expectedDefault)) {
0635:                    logln("Bug 4071859 default test passed.");
0636:                } else {
0637:                    errln("a) Failed:" + " Expected " + expectedDefault
0638:                            + " Received " + tempString);
0639:                }
0640:
0641:                formatter = NumberFormat.getCurrencyInstance(Locale.ITALY);
0642:                tempString = formatter.format(-5789.9876);
0643:
0644:                if (tempString.equals(expectedCurrency)) {
0645:                    logln("Bug 4071859 currency test passed.");
0646:                } else {
0647:                    errln("b) Failed:" + " Expected " + expectedCurrency
0648:                            + " Received " + tempString);
0649:                }
0650:
0651:                formatter = NumberFormat.getPercentInstance(Locale.ITALY);
0652:                tempString = formatter.format(-5789.9876);
0653:
0654:                if (tempString.equals(expectedPercent)) {
0655:                    logln("Bug 4071859 percentage test passed.");
0656:                } else {
0657:                    errln("c) Failed:" + " Expected " + expectedPercent
0658:                            + " Received " + tempString);
0659:                }
0660:
0661:            }
0662:
0663:            /* bug 4071859
0664:             * Test rounding for nearest even.
0665:             */
0666:            public void Test4093610() {
0667:                DecimalFormat df = new DecimalFormat("#0.#");
0668:                roundingTest(df, 12.35, "12.4");
0669:                roundingTest(df, 12.45, "12.4");
0670:                roundingTest(df, 12.452, "12.5");
0671:                roundingTest(df, 12.55, "12.6");
0672:                roundingTest(df, 12.65, "12.6");
0673:                roundingTest(df, 12.652, "12.7");
0674:                roundingTest(df, 12.75, "12.8");
0675:                roundingTest(df, 12.752, "12.8");
0676:                roundingTest(df, 12.85, "12.8");
0677:                roundingTest(df, 12.852, "12.9");
0678:                roundingTest(df, 12.95, "13");
0679:                roundingTest(df, 12.952, "13");
0680:
0681:            }
0682:
0683:            void roundingTest(DecimalFormat df, double x, String expected) {
0684:                String out = df.format(x);
0685:                logln("" + x + " formats with 1 fractional digits to " + out);
0686:                if (!out.equals(expected))
0687:                    errln("FAIL: Expected " + expected);
0688:            }
0689:
0690:            /**
0691:             * Tests the setMaximumFractionDigits limit.
0692:             */
0693:            public void Test4098741() {
0694:                try {
0695:                    NumberFormat fmt = NumberFormat.getPercentInstance();
0696:                    fmt.setMaximumFractionDigits(20);
0697:                    logln(fmt.format(.001));
0698:                } catch (Exception foo) {
0699:                    warnln("Bug 4098471 failed with exception thrown : "
0700:                            + foo.getMessage());
0701:                }
0702:            }
0703:
0704:            /**
0705:             * Tests illegal pattern exception.
0706:             * Fix comment : HShih A31 Part1 will not be fixed and javadoc needs to be updated.
0707:             * Part2 has been fixed.
0708:             */
0709:            public void Test4074454() {
0710:                try {
0711:                    DecimalFormat fmt = new DecimalFormat("#,#00.00;-#.#");
0712:                    logln("format 3456.78: " + fmt.format(3456.78)); //fix "The variable 'fmt' is never used"
0713:                    logln("Inconsistent negative pattern is fine.");
0714:                    DecimalFormat newFmt = new DecimalFormat(
0715:                            "#,#00.00 p''ieces;-#,#00.00 p''ieces");
0716:                    String tempString = newFmt.format(3456.78);
0717:                    if (!tempString.equals("3,456.78 p'ieces"))
0718:                        errln("Failed!  3456.78 p'ieces expected, but got : "
0719:                                + tempString);
0720:                } catch (Exception foo) {
0721:                    warnln("An exception was thrown for any inconsistent negative pattern.");
0722:                }
0723:            }
0724:
0725:            /**
0726:             * Tests all different comments.
0727:             * Response to some comments :
0728:             * [1] DecimalFormat.parse API documentation is more than just one line.
0729:             * This is not a reproducable doc error in 116 source code.
0730:             * [2] See updated javadoc.
0731:             * [3] Fixed.
0732:             * [4] NumberFormat.parse(String, ParsePosition) : If parsing fails,
0733:             * a null object will be returned.  The unchanged parse position also
0734:             * reflects an error.
0735:             * NumberFormat.parse(String) : If parsing fails, an ParseException
0736:             * will be thrown.
0737:             * See updated javadoc for more details.
0738:             * [5] See updated javadoc.
0739:             * [6] See updated javadoc.
0740:             * [7] This is a correct behavior if the DateFormat object is linient.
0741:             * Otherwise, an IllegalArgumentException will be thrown when formatting
0742:             * "January 35".  See GregorianCalendar class javadoc for more details.
0743:             */
0744:            public void Test4099404() {
0745:                try {
0746:                    DecimalFormat fmt = new DecimalFormat("000.0#0");
0747:                    logln("format 3456.78: " + fmt.format(3456.78)); //fix "The variable 'fmt' is never used"
0748:                    errln("Bug 4099404 failed applying illegal pattern \"000.0#0\"");
0749:                } catch (Exception foo) {
0750:                    logln("Bug 4099404 pattern \"000.0#0\" passed");
0751:                }
0752:                try {
0753:                    DecimalFormat fmt = new DecimalFormat("0#0.000");
0754:                    logln("format 3456.78: " + fmt.format(3456.78)); //fix "The variable 'fmt' is never used"
0755:                    errln("Bug 4099404 failed applying illegal pattern \"0#0.000\"");
0756:                } catch (Exception foo) {
0757:                    logln("Bug 4099404 pattern \"0#0.000\" passed");
0758:                }
0759:            }
0760:
0761:            /**
0762:             * DecimalFormat.applyPattern doesn't set minimum integer digits
0763:             */
0764:            public void Test4101481() {
0765:                DecimalFormat sdf = new DecimalFormat("#,##0");
0766:                if (sdf.getMinimumIntegerDigits() != 1)
0767:                    errln("Minimum integer digits : "
0768:                            + sdf.getMinimumIntegerDigits());
0769:            }
0770:
0771:            /**
0772:             * Tests ParsePosition.setErrorPosition() and ParsePosition.getErrorPosition().
0773:             */
0774:            public void Test4052223() {
0775:                try {
0776:                    DecimalFormat fmt = new DecimalFormat("#,#00.00");
0777:                    Number num = fmt.parse("abc3");
0778:                    errln("Bug 4052223 failed : can't parse string \"a\".  Got "
0779:                            + num);
0780:                } catch (ParseException foo) {
0781:                    logln("Caught expected ParseException : "
0782:                            + foo.getMessage() + " at index : "
0783:                            + foo.getErrorOffset());
0784:                }
0785:            }
0786:
0787:            /**
0788:             * API tests for API addition request A9.
0789:             */
0790:            public void Test4061302() {
0791:                DecimalFormatSymbols fmt = new DecimalFormatSymbols();
0792:                String currency = fmt.getCurrencySymbol();
0793:                String intlCurrency = fmt.getInternationalCurrencySymbol();
0794:                char monDecSeparator = fmt.getMonetaryDecimalSeparator();
0795:                if (currency.equals("") || intlCurrency.equals("")
0796:                        || monDecSeparator == 0) {
0797:                    errln("getCurrencySymbols failed, got empty string.");
0798:                }
0799:                logln("Before set ==> Currency : " + currency
0800:                        + " Intl Currency : " + intlCurrency
0801:                        + " Monetary Decimal Separator : " + monDecSeparator);
0802:                fmt.setCurrencySymbol("XYZ");
0803:                fmt.setInternationalCurrencySymbol("ABC");
0804:                fmt.setMonetaryDecimalSeparator('*');
0805:                currency = fmt.getCurrencySymbol();
0806:                intlCurrency = fmt.getInternationalCurrencySymbol();
0807:                monDecSeparator = fmt.getMonetaryDecimalSeparator();
0808:                if (!currency.equals("XYZ") || !intlCurrency.equals("ABC")
0809:                        || monDecSeparator != '*') {
0810:                    errln("setCurrencySymbols failed.");
0811:                }
0812:                logln("After set ==> Currency : " + currency
0813:                        + " Intl Currency : " + intlCurrency
0814:                        + " Monetary Decimal Separator : " + monDecSeparator);
0815:            }
0816:
0817:            /**
0818:             * API tests for API addition request A23. FieldPosition.getBeginIndex and
0819:             * FieldPosition.getEndIndex.
0820:             */
0821:            public void Test4062486() {
0822:                DecimalFormat fmt = new DecimalFormat("#,##0.00");
0823:                StringBuffer formatted = new StringBuffer();
0824:                FieldPosition field = new FieldPosition(0);
0825:                Double num = new Double(1234.5);
0826:                fmt.format(num, formatted, field);
0827:                if (field.getBeginIndex() != 0 && field.getEndIndex() != 5)
0828:                    errln("Format 1234.5 failed. Begin index: "
0829:                            + field.getBeginIndex() + " End index: "
0830:                            + field.getEndIndex());
0831:                field.setBeginIndex(7);
0832:                field.setEndIndex(4);
0833:                if (field.getBeginIndex() != 7 && field.getEndIndex() != 4)
0834:                    errln("Set begin/end field indexes failed. Begin index: "
0835:                            + field.getBeginIndex() + " End index: "
0836:                            + field.getEndIndex());
0837:            }
0838:
0839:            /**
0840:             * DecimalFormat.parse incorrectly works with a group separator.
0841:             */
0842:            public void Test4108738() {
0843:
0844:                DecimalFormat df = new DecimalFormat("#,##0.###",
0845:                        new DecimalFormatSymbols(java.util.Locale.US));
0846:                String text = "1.222,111";
0847:                Number num = df.parse(text, new ParsePosition(0));
0848:                if (!num.toString().equals("1.222"))
0849:                    errln("\"" + text + "\"  is parsed as " + num);
0850:                text = "1.222x111";
0851:                num = df.parse(text, new ParsePosition(0));
0852:                if (!num.toString().equals("1.222"))
0853:                    errln("\"" + text + "\"  is parsed as " + num);
0854:            }
0855:
0856:            /**
0857:             * DecimalFormat.format() incorrectly formats negative doubles.
0858:             */
0859:            public void Test4106658() {
0860:                Locale savedLocale = Locale.getDefault();
0861:                Locale.setDefault(Locale.US);
0862:                DecimalFormat df = new DecimalFormat(); // Corrected; see 4147706
0863:                double d1 = -0.0;
0864:                double d2 = -0.0001;
0865:                StringBuffer buffer = new StringBuffer();
0866:                logln("pattern: \"" + df.toPattern() + "\"");
0867:                df.format(d1, buffer, new FieldPosition(0));
0868:                if (!buffer.toString().equals("-0")) { // Corrected; see 4147706
0869:                    errln(d1 + "      is formatted as " + buffer);
0870:                }
0871:                buffer.setLength(0);
0872:                df.format(d2, buffer, new FieldPosition(0));
0873:                if (!buffer.toString().equals("-0")) { // Corrected; see 4147706
0874:                    errln(d2 + "      is formatted as " + buffer);
0875:                }
0876:                Locale.setDefault(savedLocale);
0877:            }
0878:
0879:            /**
0880:             * DecimalFormat.parse returns 0 if string parameter is incorrect.
0881:             */
0882:            public void Test4106662() {
0883:                DecimalFormat df = new DecimalFormat();
0884:                String text = "x";
0885:                ParsePosition pos1 = new ParsePosition(0), pos2 = new ParsePosition(
0886:                        0);
0887:
0888:                logln("pattern: \"" + df.toPattern() + "\"");
0889:                Number num = df.parse(text, pos1);
0890:                if (num != null) {
0891:                    errln("Test Failed: \"" + text + "\" is parsed as " + num);
0892:                }
0893:                df = null;
0894:                df = new DecimalFormat("$###.00");
0895:                num = df.parse("$", pos2);
0896:                if (num != null) {
0897:                    errln("Test Failed: \"$\" is parsed as " + num);
0898:                }
0899:            }
0900:
0901:            /**
0902:             * NumberFormat.parse doesn't return null
0903:             */
0904:            public void Test4114639() {
0905:                NumberFormat format = NumberFormat.getInstance();
0906:                String text = "time 10:x";
0907:                ParsePosition pos = new ParsePosition(8);
0908:                Number result = format.parse(text, pos);
0909:                if (result != null)
0910:                    errln("Should return null but got : " + result); // Should be null; it isn't
0911:            }
0912:
0913:            /**
0914:             * DecimalFormat.format(long n) fails if n * multiplier > MAX_LONG.
0915:             */
0916:            public void Test4106664() {
0917:                DecimalFormat df = new DecimalFormat();
0918:                long n = 1234567890123456L;
0919:                int m = 12345678;
0920:                BigInteger bigN = BigInteger.valueOf(n);
0921:                bigN = bigN.multiply(BigInteger.valueOf(m));
0922:                df.setMultiplier(m);
0923:                df.setGroupingUsed(false);
0924:                logln("formated: "
0925:                        + df
0926:                                .format(n, new StringBuffer(),
0927:                                        new FieldPosition(0)));
0928:                logln("expected: " + bigN.toString());
0929:            }
0930:
0931:            /**
0932:             * DecimalFormat.format incorrectly formats -0.0.
0933:             */
0934:            public void Test4106667() {
0935:                Locale savedLocale = Locale.getDefault();
0936:                Locale.setDefault(Locale.US);
0937:                DecimalFormat df = new DecimalFormat();
0938:                df.setPositivePrefix("+");
0939:                double d = -0.0;
0940:                logln("pattern: \"" + df.toPattern() + "\"");
0941:                StringBuffer buffer = new StringBuffer();
0942:                df.format(d, buffer, new FieldPosition(0));
0943:                if (!buffer.toString().equals("-0")) { // Corrected; see 4147706
0944:                    errln(d + "  is formatted as " + buffer);
0945:                }
0946:                Locale.setDefault(savedLocale);
0947:            }
0948:
0949:            /**
0950:             * DecimalFormat.setMaximumIntegerDigits() works incorrectly.
0951:             */
0952:            public void Test4110936() {
0953:                NumberFormat nf = NumberFormat.getInstance();
0954:                nf.setMaximumIntegerDigits(128);
0955:                logln("setMaximumIntegerDigits(128)");
0956:                if (nf.getMaximumIntegerDigits() != 128)
0957:                    errln("getMaximumIntegerDigits() returns "
0958:                            + nf.getMaximumIntegerDigits());
0959:            }
0960:
0961:            /**
0962:             * Locale data should use generic currency symbol
0963:             *
0964:             * 1) Make sure that all currency formats use the generic currency symbol.
0965:             * 2) Make sure we get the same results using the generic symbol or a
0966:             *    hard-coded one.
0967:             */
0968:            public void Test4122840() {
0969:                Locale[] locales = NumberFormat.getAvailableLocales();
0970:
0971:                for (int i = 0; i < locales.length; i++) {
0972:                    ICUResourceBundle rb = (ICUResourceBundle) UResourceBundle
0973:                            .getBundleInstance(ICUResourceBundle.ICU_BASE_NAME,
0974:                                    locales[i]);
0975:
0976:                    //
0977:                    // Get the currency pattern for this locale.  We have to fish it
0978:                    // out of the ResourceBundle directly, since DecimalFormat.toPattern
0979:                    // will return the localized symbol, not \00a4
0980:                    //
0981:                    ICUResourceBundle numPatterns = rb.get("NumberPatterns");
0982:                    String pattern = numPatterns.getString(1);
0983:
0984:                    if (pattern.indexOf('\u00A4') == -1) { // 'x' not "x" -- workaround bug in IBM JDK 1.4.1
0985:                        errln("Currency format for " + locales[i]
0986:                                + " does not contain generic currency symbol:"
0987:                                + pattern);
0988:                    }
0989:
0990:                    // Create a DecimalFormat using the pattern we got and format a number
0991:                    DecimalFormatSymbols symbols = new DecimalFormatSymbols(
0992:                            locales[i]);
0993:                    DecimalFormat fmt1 = new DecimalFormat(pattern, symbols);
0994:
0995:                    String result1 = fmt1.format(1.111);
0996:
0997:                    //
0998:                    // Now substitute in the locale's currency symbol and create another
0999:                    // pattern.  Replace the decimal separator with the monetary separator.
1000:                    //
1001:                    //char decSep = symbols.getDecimalSeparator(); //The variable is never used
1002:                    char monSep = symbols.getMonetaryDecimalSeparator();
1003:                    StringBuffer buf = new StringBuffer(pattern);
1004:                    for (int j = 0; j < buf.length(); j++) {
1005:                        if (buf.charAt(j) == '\u00a4') {
1006:                            String cur = "'" + symbols.getCurrencySymbol()
1007:                                    + "'";
1008:                            buf.replace(j, j + 1, cur);
1009:                            j += cur.length() - 1;
1010:                        }
1011:                    }
1012:                    symbols.setDecimalSeparator(monSep);
1013:                    DecimalFormat fmt2 = new DecimalFormat(buf.toString(),
1014:                            symbols);
1015:
1016:                    String result2 = fmt2.format(1.111);
1017:
1018:                    // NOTE: en_IN is a special case (ChoiceFormat currency display name)
1019:                    if (!result1.equals(result2)
1020:                            && !locales[i].toString().equals("en_IN")) {
1021:                        errln("Results for " + locales[i] + " differ: "
1022:                                + result1 + " vs " + result2);
1023:                    }
1024:                }
1025:            }
1026:
1027:            /**
1028:             * DecimalFormat.format() delivers wrong string.
1029:             */
1030:            public void Test4125885() {
1031:                double rate = 12.34;
1032:                DecimalFormat formatDec = new DecimalFormat("000.00");
1033:                logln("toPattern: " + formatDec.toPattern());
1034:                String rateString = formatDec.format(rate);
1035:                if (!rateString.equals("012.34"))
1036:                    errln("result : " + rateString + " expected : 012.34");
1037:                rate = 0.1234;
1038:                formatDec = null;
1039:                formatDec = new DecimalFormat("+000.00%;-000.00%");
1040:                logln("toPattern: " + formatDec.toPattern());
1041:                rateString = formatDec.format(rate);
1042:                if (!rateString.equals("+012.34%"))
1043:                    errln("result : " + rateString + " expected : +012.34%");
1044:            }
1045:
1046:            /**
1047:             **
1048:             * DecimalFormat produces extra zeros when formatting numbers.
1049:             */
1050:            public void Test4134034() {
1051:                DecimalFormat nf = new DecimalFormat("##,###,###.00");
1052:
1053:                String f = nf.format(9.02);
1054:                if (f.equals("9.02"))
1055:                    logln(f + " ok");
1056:                else
1057:                    errln("9.02 -> " + f + "; want 9.02");
1058:
1059:                f = nf.format(0);
1060:                if (f.equals(".00"))
1061:                    logln(f + " ok");
1062:                else
1063:                    errln("0 -> " + f + "; want .00");
1064:            }
1065:
1066:            /**
1067:             * CANNOT REPRODUCE - This bug could not be reproduced.  It may be
1068:             * a duplicate of 4134034.
1069:             *
1070:             * JDK 1.1.6 Bug, did NOT occur in 1.1.5
1071:             * Possibly related to bug 4125885.
1072:             * 
1073:             * This class demonstrates a regression in version 1.1.6
1074:             * of DecimalFormat class.
1075:             * 
1076:             * 1.1.6 Results
1077:             * Value 1.2 Format #.00 Result '01.20' !!!wrong
1078:             * Value 1.2 Format 0.00 Result '001.20' !!!wrong
1079:             * Value 1.2 Format 00.00 Result '0001.20' !!!wrong
1080:             * Value 1.2 Format #0.0# Result '1.2'
1081:             * Value 1.2 Format #0.00 Result '001.20' !!!wrong
1082:             * 
1083:             * 1.1.5 Results
1084:             * Value 1.2 Format #.00 Result '1.20'
1085:             * Value 1.2 Format 0.00 Result '1.20'
1086:             * Value 1.2 Format 00.00 Result '01.20'
1087:             * Value 1.2 Format #0.0# Result '1.2'
1088:             * Value 1.2 Format #0.00 Result '1.20'
1089:             */
1090:            public void Test4134300() {
1091:                String[] DATA = {
1092:                        // Pattern      Expected string
1093:                        "#.00", "1.20", "0.00", "1.20", "00.00", "01.20",
1094:                        "#0.0#", "1.2", "#0.00", "1.20", };
1095:                for (int i = 0; i < DATA.length; i += 2) {
1096:                    String result = new DecimalFormat(DATA[i]).format(1.2);
1097:                    if (!result.equals(DATA[i + 1])) {
1098:                        errln("Fail: 1.2 x " + DATA[i] + " = " + result
1099:                                + "; want " + DATA[i + 1]);
1100:                    } else {
1101:                        logln("Ok: 1.2 x " + DATA[i] + " = " + result);
1102:                    }
1103:                }
1104:            }
1105:
1106:            /**
1107:             * Empty pattern produces double negative prefix.
1108:             */
1109:            public void Test4140009() {
1110:                final double IN[] = { 123.456, -123.456 };
1111:                final String OUT[] = { "123.456", "-123.456" };
1112:                for (int i = 0; i < 2; ++i) {
1113:                    DecimalFormat f = null;
1114:                    switch (i) {
1115:                    case 0:
1116:                        f = new DecimalFormat("", new DecimalFormatSymbols(
1117:                                Locale.ENGLISH));
1118:                        break;
1119:                    case 1:
1120:                        f = new DecimalFormat("#.#", new DecimalFormatSymbols(
1121:                                Locale.ENGLISH));
1122:                        f.applyPattern("");
1123:                        break;
1124:                    }
1125:                    for (int j = 0; j < 2; ++j) {
1126:                        assertEquals("<empty pat " + i + ">.format(" + IN[j]
1127:                                + ")", OUT[j], f.format(IN[j]));
1128:                    }
1129:                }
1130:            }
1131:
1132:            //#ifndef FOUNDATION
1133:            /**
1134:             * BigDecimal numbers get their fractions truncated by NumberFormat.
1135:             */
1136:            public void Test4141750() {
1137:                try {
1138:                    String str = "12345.67";
1139:                    BigDecimal bd = new BigDecimal(str);
1140:                    String sd = NumberFormat.getInstance(Locale.US).format(bd);
1141:                    if (!sd.endsWith("67"))
1142:                        errln("Fail: " + str + " x format -> " + sd);
1143:                } catch (Exception e) {
1144:                    warnln(e.toString());
1145:                    //e.printStackTrace();
1146:                }
1147:            }
1148:
1149:            //#endif
1150:
1151:            /**
1152:             * DecimalFormat toPattern() doesn't quote special characters or handle
1153:             * single quotes.
1154:             */
1155:            public void Test4145457() {
1156:                try {
1157:                    DecimalFormat nf = (DecimalFormat) NumberFormat
1158:                            .getInstance();
1159:                    DecimalFormatSymbols sym = nf.getDecimalFormatSymbols();
1160:                    sym.setDecimalSeparator('\'');
1161:                    nf.setDecimalFormatSymbols(sym);
1162:                    double pi = 3.14159;
1163:
1164:                    String[] PATS = { "#.00 'num''ber'", "''#.00''" };
1165:
1166:                    for (int i = 0; i < PATS.length; ++i) {
1167:                        nf.applyPattern(PATS[i]);
1168:                        String out = nf.format(pi);
1169:                        String pat = nf.toPattern();
1170:                        double val = nf.parse(out).doubleValue();
1171:
1172:                        nf.applyPattern(pat);
1173:                        String out2 = nf.format(pi);
1174:                        String pat2 = nf.toPattern();
1175:                        double val2 = nf.parse(out2).doubleValue();
1176:
1177:                        if (!pat.equals(pat2))
1178:                            errln("Fail with \"" + PATS[i]
1179:                                    + "\": Patterns should concur, \"" + pat
1180:                                    + "\" vs. \"" + pat2 + "\"");
1181:                        else
1182:                            logln("Ok \"" + PATS[i] + "\" toPattern() -> \""
1183:                                    + pat + '"');
1184:
1185:                        if (val == val2 && out.equals(out2)) {
1186:                            logln("Ok " + pi + " x \"" + PATS[i] + "\" -> \""
1187:                                    + out + "\" -> " + val + " -> \"" + out2
1188:                                    + "\" -> " + val2);
1189:                        } else {
1190:                            errln("Fail " + pi + " x \"" + PATS[i] + "\" -> \""
1191:                                    + out + "\" -> " + val + " -> \"" + out2
1192:                                    + "\" -> " + val2);
1193:                        }
1194:                    }
1195:                } catch (ParseException e) {
1196:                    errln("Fail: " + e);
1197:                    e.printStackTrace();
1198:                }
1199:            }
1200:
1201:            /**
1202:             * DecimalFormat.applyPattern() sets minimum integer digits incorrectly.
1203:             * CANNOT REPRODUCE
1204:             * This bug is a duplicate of 4139344, which is a duplicate of 4134300
1205:             */
1206:            public void Test4147295() {
1207:                DecimalFormat sdf = new DecimalFormat();
1208:                String pattern = "#,###";
1209:                logln("Applying pattern \"" + pattern + "\"");
1210:                sdf.applyPattern(pattern);
1211:                int minIntDig = sdf.getMinimumIntegerDigits();
1212:                if (minIntDig != 0) {
1213:                    errln("Test failed");
1214:                    errln(" Minimum integer digits : " + minIntDig);
1215:                    errln(" new pattern: " + sdf.toPattern());
1216:                } else {
1217:                    logln("Test passed");
1218:                    logln(" Minimum integer digits : " + minIntDig);
1219:                }
1220:            }
1221:
1222:            /**
1223:             * DecimalFormat formats -0.0 as +0.0
1224:             * See also older related bug 4106658, 4106667
1225:             */
1226:            public void Test4147706() {
1227:                DecimalFormat df = new DecimalFormat("#,##0.0##");
1228:                df.setDecimalFormatSymbols(new DecimalFormatSymbols(
1229:                        Locale.ENGLISH));
1230:                double d1 = -0.0;
1231:                double d2 = -0.0001;
1232:                StringBuffer f1 = df.format(d1, new StringBuffer(),
1233:                        new FieldPosition(0));
1234:                StringBuffer f2 = df.format(d2, new StringBuffer(),
1235:                        new FieldPosition(0));
1236:                if (!f1.toString().equals("-0.0")) {
1237:                    errln(d1 + " x \"" + df.toPattern()
1238:                            + "\" is formatted as \"" + f1 + '"');
1239:                }
1240:                if (!f2.toString().equals("-0.0")) {
1241:                    errln(d2 + " x \"" + df.toPattern()
1242:                            + "\" is formatted as \"" + f2 + '"');
1243:                }
1244:            }
1245:
1246:            /**
1247:             * NumberFormat cannot format Double.MAX_VALUE
1248:             */
1249:            public void Test4162198() {
1250:                double dbl = Double.MAX_VALUE;
1251:                NumberFormat f = NumberFormat.getInstance();
1252:                f.setMaximumFractionDigits(Integer.MAX_VALUE);
1253:                f.setMaximumIntegerDigits(Integer.MAX_VALUE);
1254:                String s = f.format(dbl);
1255:                logln("The number " + dbl + " formatted to " + s);
1256:                Number n = null;
1257:                try {
1258:                    n = f.parse(s);
1259:                } catch (java.text.ParseException e) {
1260:                    errln("Caught a ParseException:");
1261:                    e.printStackTrace();
1262:                }
1263:                logln("The string " + s + " parsed as " + n);
1264:                if (n.doubleValue() != dbl) {
1265:                    errln("Round trip failure");
1266:                }
1267:            }
1268:
1269:            /**
1270:             * NumberFormat does not parse negative zero.
1271:             */
1272:            public void Test4162852() throws ParseException {
1273:                for (int i = 0; i < 2; ++i) {
1274:                    NumberFormat f = (i == 0) ? NumberFormat.getInstance()
1275:                            : NumberFormat.getPercentInstance();
1276:                    double d = -0.0;
1277:                    String s = f.format(d);
1278:                    double e = f.parse(s).doubleValue();
1279:                    logln("" + d + " -> " + '"' + s + '"' + " -> " + e);
1280:                    if (e != 0.0 || 1.0 / e > 0.0) {
1281:                        logln("Failed to parse negative zero");
1282:                    }
1283:                }
1284:            }
1285:
1286:            /**
1287:             * NumberFormat truncates data
1288:             */
1289:            public void Test4167494() throws Exception {
1290:                NumberFormat fmt = NumberFormat.getInstance(Locale.US);
1291:
1292:                double a = Double.MAX_VALUE;
1293:                String s = fmt.format(a);
1294:                double b = fmt.parse(s).doubleValue();
1295:                boolean match = a == b;
1296:                if (match) {
1297:                    logln("" + a + " -> \"" + s + "\" -> " + b + " ok");
1298:                } else {
1299:                    errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL");
1300:                }
1301:
1302:                // We don't test Double.MIN_VALUE because the locale data for the US
1303:                // currently doesn't specify enough digits to display Double.MIN_VALUE.
1304:                // This is correct for now; however, we leave this here as a reminder
1305:                // in case we want to address this later.
1306:                if (false) {
1307:                    a = Double.MIN_VALUE;
1308:                    s = fmt.format(a);
1309:                    b = fmt.parse(s).doubleValue();
1310:                    match = a == b;
1311:                    if (match) {
1312:                        logln("" + a + " -> \"" + s + "\" -> " + b + " ok");
1313:                    } else {
1314:                        errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL");
1315:                    }
1316:                }
1317:            }
1318:
1319:            /**
1320:             * DecimalFormat.parse() fails when ParseIntegerOnly set to true
1321:             */
1322:            public void Test4170798() {
1323:                Locale savedLocale = Locale.getDefault();
1324:                Locale.setDefault(Locale.US);
1325:                DecimalFormat df = new DecimalFormat();
1326:                df.setParseIntegerOnly(true);
1327:                Number n = df.parse("-0.0", new ParsePosition(0));
1328:                if (!(n instanceof  Double) || n.intValue() != 0) {
1329:                    errln("FAIL: parse(\"-0.0\") returns " + n + " ("
1330:                            + n.getClass().getName() + ')');
1331:                }
1332:                Locale.setDefault(savedLocale);
1333:            }
1334:
1335:            /**
1336:             * toPattern only puts the first grouping separator in.
1337:             */
1338:            public void Test4176114() {
1339:                String[] DATA = { "00", "#00",
1340:                        "000",
1341:                        "#000", // No grouping
1342:                        "#000",
1343:                        "#000", // No grouping
1344:                        "#,##0", "#,##0", "#,000", "#,000", "0,000", "#0,000",
1345:                        "00,000", "#00,000", "000,000", "#,000,000",
1346:                        "0,000,000,000,000.0000", "#0,000,000,000,000.0000", // Reported
1347:                };
1348:                for (int i = 0; i < DATA.length; i += 2) {
1349:                    DecimalFormat df = new DecimalFormat(DATA[i]);
1350:                    String s = df.toPattern();
1351:                    if (!s.equals(DATA[i + 1])) {
1352:                        errln("FAIL: " + DATA[i] + " -> " + s + ", want "
1353:                                + DATA[i + 1]);
1354:                    }
1355:                }
1356:            }
1357:
1358:            /**
1359:             * DecimalFormat is incorrectly rounding numbers like 1.2501 to 1.2
1360:             */
1361:            public void Test4179818() {
1362:                String DATA[] = {
1363:                        // Input  Pattern  Expected output
1364:                        "1.2511", "#.#", "1.3", "1.2501", "#.#", "1.3",
1365:                        "0.9999", "#", "1", };
1366:                DecimalFormat fmt = new DecimalFormat("#",
1367:                        new DecimalFormatSymbols(Locale.US));
1368:                for (int i = 0; i < DATA.length; i += 3) {
1369:                    double in = Double.valueOf(DATA[i]).doubleValue();
1370:                    String pat = DATA[i + 1];
1371:                    String exp = DATA[i + 2];
1372:                    fmt.applyPattern(pat);
1373:                    String out = fmt.format(in);
1374:                    if (out.equals(exp)) {
1375:                        logln("Ok: " + in + " x " + pat + " = " + out);
1376:                    } else {
1377:                        errln("FAIL: " + in + " x  " + pat + " = " + out
1378:                                + ", expected " + exp);
1379:                    }
1380:                }
1381:            }
1382:
1383:            public void Test4185761() throws IOException,
1384:                    ClassNotFoundException {
1385:                ByteArrayOutputStream baos = new ByteArrayOutputStream();
1386:                ObjectOutputStream oos = new ObjectOutputStream(baos);
1387:
1388:                NumberFormat nf = NumberFormat.getInstance(Locale.US);
1389:
1390:                // Set special values we are going to search for in the output byte stream
1391:                // These are all legal values.
1392:                nf.setMinimumIntegerDigits(0x111); // Keep under 309
1393:                nf.setMaximumIntegerDigits(0x112); // Keep under 309
1394:                nf.setMinimumFractionDigits(0x113); // Keep under 340
1395:                nf.setMaximumFractionDigits(0x114); // Keep under 340
1396:
1397:                oos.writeObject(nf);
1398:                oos.flush();
1399:                baos.close();
1400:
1401:                byte[] bytes = baos.toByteArray();
1402:
1403:                // Scan for locations of min/max int/fract values in the byte array.
1404:                // At the moment (ICU4J 2.1), there is only one instance of each target pair
1405:                // in the byte stream, so assume first match is it.  Note this is not entirely
1406:                // failsafe, and needs to be checked if we change the package or structure of
1407:                // this class.
1408:                // Current positions are 890, 880, 886, 876
1409:                int[] offsets = new int[4];
1410:                for (int i = 0; i < bytes.length - 1; ++i) {
1411:                    if (bytes[i] == 0x01) { // high byte
1412:                        for (int j = 0; j < offsets.length; ++j) {
1413:                            if ((offsets[j] == 0)
1414:                                    && (bytes[i + 1] == (0x11 + j))) { // low byte
1415:                                offsets[j] = i;
1416:                                break;
1417:                            }
1418:                        }
1419:                    }
1420:                }
1421:
1422:                {
1423:                    ObjectInputStream ois = new ObjectInputStream(
1424:                            new ByteArrayInputStream(bytes));
1425:                    Object o = ois.readObject();
1426:                    ois.close();
1427:
1428:                    if (!nf.equals(o)) {
1429:                        errln("Fail: DateFormat serialization/equality bug");
1430:                    } else {
1431:                        logln("DateFormat serialization/equality is OKAY.");
1432:                    }
1433:                }
1434:
1435:                // Change the values in the byte stream so that min > max.
1436:                // Numberformat should catch this and throw an exception.
1437:                for (int i = 0; i < offsets.length; ++i) {
1438:                    bytes[offsets[i]] = (byte) (4 - i);
1439:                }
1440:
1441:                {
1442:                    ObjectInputStream ois = new ObjectInputStream(
1443:                            new ByteArrayInputStream(bytes));
1444:                    try {
1445:                        NumberFormat format = (NumberFormat) ois.readObject();
1446:                        logln("format: " + format.format(1234.56)); //fix "The variable is never used"
1447:                        errln("FAIL: Deserialized bogus NumberFormat with minXDigits > maxXDigits");
1448:                    } catch (InvalidObjectException e) {
1449:                        logln("Ok: " + e.getMessage());
1450:                    }
1451:                }
1452:
1453:                // Set values so they are too high, but min <= max
1454:                // Format should pass the min <= max test, and DecimalFormat should reset to current maximum
1455:                // (for compatibility with versions streamed out before the maximums were imposed).
1456:                for (int i = 0; i < offsets.length; ++i) {
1457:                    bytes[offsets[i]] = 4;
1458:                }
1459:
1460:                {
1461:                    ObjectInputStream ois = new ObjectInputStream(
1462:                            new ByteArrayInputStream(bytes));
1463:                    NumberFormat format = (NumberFormat) ois.readObject();
1464:                    //For compatibility with previous version
1465:                    if ((format.getMaximumIntegerDigits() != 309)
1466:                            || format.getMaximumFractionDigits() != 340) {
1467:                        errln("FAIL: Deserialized bogus NumberFormat with values out of range,"
1468:                                + " intMin: "
1469:                                + format.getMinimumIntegerDigits()
1470:                                + " intMax: "
1471:                                + format.getMaximumIntegerDigits()
1472:                                + " fracMin: "
1473:                                + format.getMinimumFractionDigits()
1474:                                + " fracMax: "
1475:                                + format.getMaximumFractionDigits());
1476:                    } else {
1477:                        logln("Ok: Digit count out of range");
1478:                    }
1479:                }
1480:            }
1481:
1482:            /**
1483:             * Some DecimalFormatSymbols changes are not picked up by DecimalFormat.
1484:             * This includes the minus sign, currency symbol, international currency
1485:             * symbol, percent, and permille.  This is filed as bugs 4212072 and
1486:             * 4212073.
1487:             */
1488:            public void Test4212072() throws IOException,
1489:                    ClassNotFoundException {
1490:                DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
1491:                DecimalFormat fmt = new DecimalFormat("#", sym);
1492:
1493:                sym.setMinusSign('^');
1494:                fmt.setDecimalFormatSymbols(sym);
1495:                if (!fmt.format(-1).equals("^1")) {
1496:                    errln("FAIL: -1 x (minus=^) -> " + fmt.format(-1)
1497:                            + ", exp ^1");
1498:                }
1499:                if (!fmt.getNegativePrefix().equals("^")) {
1500:                    errln("FAIL: (minus=^).getNegativePrefix -> "
1501:                            + fmt.getNegativePrefix() + ", exp ^");
1502:                }
1503:                sym.setMinusSign('-');
1504:
1505:                fmt.applyPattern("#%");
1506:                sym.setPercent('^');
1507:                fmt.setDecimalFormatSymbols(sym);
1508:                if (!fmt.format(0.25).equals("25^")) {
1509:                    errln("FAIL: 0.25 x (percent=^) -> " + fmt.format(0.25)
1510:                            + ", exp 25^");
1511:                }
1512:                if (!fmt.getPositiveSuffix().equals("^")) {
1513:                    errln("FAIL: (percent=^).getPositiveSuffix -> "
1514:                            + fmt.getPositiveSuffix() + ", exp ^");
1515:                }
1516:                sym.setPercent('%');
1517:
1518:                fmt.applyPattern("#\u2030");
1519:                sym.setPerMill('^');
1520:                fmt.setDecimalFormatSymbols(sym);
1521:                if (!fmt.format(0.25).equals("250^")) {
1522:                    errln("FAIL: 0.25 x (permill=^) -> " + fmt.format(0.25)
1523:                            + ", exp 250^");
1524:                }
1525:                if (!fmt.getPositiveSuffix().equals("^")) {
1526:                    errln("FAIL: (permill=^).getPositiveSuffix -> "
1527:                            + fmt.getPositiveSuffix() + ", exp ^");
1528:                }
1529:                sym.setPerMill('\u2030');
1530:
1531:                fmt.applyPattern("\u00A4#.00");
1532:                sym.setCurrencySymbol("usd");
1533:                fmt.setDecimalFormatSymbols(sym);
1534:                if (!fmt.format(12.5).equals("usd12.50")) {
1535:                    errln("FAIL: 12.5 x (currency=usd) -> " + fmt.format(12.5)
1536:                            + ", exp usd12.50");
1537:                }
1538:                if (!fmt.getPositivePrefix().equals("usd")) {
1539:                    errln("FAIL: (currency=usd).getPositivePrefix -> "
1540:                            + fmt.getPositivePrefix() + ", exp usd");
1541:                }
1542:                sym.setCurrencySymbol("$");
1543:
1544:                fmt.applyPattern("\u00A4\u00A4#.00");
1545:                sym.setInternationalCurrencySymbol("DOL");
1546:                fmt.setDecimalFormatSymbols(sym);
1547:                if (!fmt.format(12.5).equals("DOL12.50")) {
1548:                    errln("FAIL: 12.5 x (intlcurrency=DOL) -> "
1549:                            + fmt.format(12.5) + ", exp DOL12.50");
1550:                }
1551:                if (!fmt.getPositivePrefix().equals("DOL")) {
1552:                    errln("FAIL: (intlcurrency=DOL).getPositivePrefix -> "
1553:                            + fmt.getPositivePrefix() + ", exp DOL");
1554:                }
1555:                sym.setInternationalCurrencySymbol("USD");
1556:
1557:                if (VersionInfo.ICU_VERSION == VersionInfo.getInstance(2, 2)) {
1558:                    // bug in 2.2 that fails this test
1559:                    // to be fixed in the later versions
1560:                    System.out
1561:                            .println("\n        Test skipped for release 2.2");
1562:                    return;
1563:                }
1564:
1565:                // Since the pattern logic has changed, make sure that patterns round
1566:                // trip properly.  Test stream in/out integrity too.
1567:                Locale[] avail = NumberFormat.getAvailableLocales();
1568:                for (int i = 0; i < avail.length; ++i) {
1569:                    for (int j = 0; j < 3; ++j) {
1570:                        NumberFormat nf;
1571:                        switch (j) {
1572:                        case 0:
1573:                            nf = NumberFormat.getInstance(avail[i]);
1574:                            break;
1575:                        case 1:
1576:                            nf = NumberFormat.getCurrencyInstance(avail[i]);
1577:                            break;
1578:                        default:
1579:                            nf = NumberFormat.getPercentInstance(avail[i]);
1580:                            break;
1581:                        }
1582:                        DecimalFormat df = (DecimalFormat) nf;
1583:
1584:                        // Test toPattern/applyPattern round trip
1585:                        String pat = df.toPattern();
1586:                        DecimalFormatSymbols symb = new DecimalFormatSymbols(
1587:                                avail[i]);
1588:                        DecimalFormat f2 = new DecimalFormat(pat, symb);
1589:                        if (!df.equals(f2)) {
1590:                            errln("FAIL: " + avail[i] + " #" + j + " -> \""
1591:                                    + pat + "\" -> \"" + f2.toPattern() + '"');
1592:                        }
1593:
1594:                        // Test toLocalizedPattern/applyLocalizedPattern round trip
1595:                        pat = df.toLocalizedPattern();
1596:                        try {
1597:                            f2.applyLocalizedPattern(pat);
1598:
1599:                            String s1 = f2.format(123456);
1600:                            String s2 = df.format(123456);
1601:                            if (!s1.equals(s2)) {
1602:                                errln("FAIL: " + avail[i] + " #" + j
1603:                                        + " -> localized \"" + s2 + "\" -> \""
1604:                                        + s2 + '"' + " in locale "
1605:                                        + df.getLocale(ULocale.ACTUAL_LOCALE));
1606:
1607:                            }
1608:                            if (!df.equals(f2)) {
1609:                                errln("FAIL: " + avail[i] + " #" + j
1610:                                        + " -> localized \"" + pat + "\" -> \""
1611:                                        + f2.toLocalizedPattern() + '"'
1612:                                        + " in locale "
1613:                                        + df.getLocale(ULocale.ACTUAL_LOCALE));
1614:                                errln("s1: " + s1 + " s2: " + s2);
1615:                            }
1616:
1617:                        } catch (IllegalArgumentException ex) {
1618:                            errln(ex.getMessage() + " for locale "
1619:                                    + df.getLocale(ULocale.ACTUAL_LOCALE));
1620:                        }
1621:
1622:                        // Test writeObject/readObject round trip
1623:                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
1624:                        ObjectOutputStream oos = new ObjectOutputStream(baos);
1625:                        oos.writeObject(df);
1626:                        oos.flush();
1627:                        baos.close();
1628:                        byte[] bytes = baos.toByteArray();
1629:                        ObjectInputStream ois = new ObjectInputStream(
1630:                                new ByteArrayInputStream(bytes));
1631:                        f2 = (DecimalFormat) ois.readObject();
1632:                        if (!df.equals(f2)) {
1633:                            errln("FAIL: Stream in/out "
1634:                                    + avail[i]
1635:                                    + " -> \""
1636:                                    + pat
1637:                                    + "\" -> "
1638:                                    + (f2 != null ? ("\"" + f2.toPattern() + '"')
1639:                                            : "null"));
1640:                        }
1641:
1642:                    }
1643:                }
1644:
1645:                // @since ICU 2.4
1646:                // Make sure that all special characters, when quoted in a suffix or
1647:                // prefix, lose their special meaning.
1648:                char[] SPECIALS = { '0', ',', '.', '\u2030', '%', '#', ';',
1649:                        'E', '*', '+', '-' };
1650:                sym = new DecimalFormatSymbols(Locale.US);
1651:                for (int j = 0; j < SPECIALS.length; ++j) {
1652:                    char special = SPECIALS[j];
1653:                    String pat = "'" + special + "'#0'" + special + "'";
1654:                    try {
1655:                        fmt = new DecimalFormat(pat, sym);
1656:                        String pat2 = fmt.toPattern();
1657:                        if (!pat.equals(pat2)) {
1658:                            errln("FAIL: Pattern \"" + pat
1659:                                    + "\" => toPattern() => \"" + pat2 + "\"");
1660:                        }
1661:                        String s = fmt.format(123);
1662:                        String exp = "" + special + "123" + special;
1663:                        if (!s.equals(exp)) {
1664:                            errln("FAIL: 123 x \"" + pat + "\" => \"" + s
1665:                                    + "\", exp \"" + exp + "\"");
1666:                        }
1667:                    } catch (IllegalArgumentException e) {
1668:                        errln("FAIL: Pattern \"" + pat + "\" => "
1669:                                + e.getMessage());
1670:                    }
1671:                }
1672:            }
1673:
1674:            /**
1675:             * DecimalFormat.parse() fails for mulipliers 2^n.
1676:             */
1677:            public void Test4216742() throws ParseException {
1678:                DecimalFormat fmt = (DecimalFormat) NumberFormat
1679:                        .getInstance(Locale.US);
1680:                long[] DATA = { Long.MIN_VALUE, Long.MAX_VALUE, -100000000L,
1681:                        100000000L };
1682:                for (int i = 0; i < DATA.length; ++i) {
1683:                    String str = Long.toString(DATA[i]);
1684:                    for (int m = 1; m <= 100; m++) {
1685:                        fmt.setMultiplier(m);
1686:                        long n = ((Number) fmt.parse(str)).longValue();
1687:                        if (n > 0 != DATA[i] > 0) {
1688:                            errln("\"" + str + "\" parse(x "
1689:                                    + fmt.getMultiplier() + ") => " + n);
1690:                        }
1691:                    }
1692:                }
1693:            }
1694:
1695:            /**
1696:             * DecimalFormat formats 1.001 to "1.00" instead of "1" with 2 fraction
1697:             * digits.
1698:             */
1699:            public void Test4217661() {
1700:                Object[] DATA = { new Double(0.001), "0", new Double(1.001),
1701:                        "1", new Double(0.006), "0.01", new Double(1.006),
1702:                        "1.01", };
1703:                NumberFormat fmt = NumberFormat.getInstance(Locale.US);
1704:                fmt.setMaximumFractionDigits(2);
1705:                for (int i = 0; i < DATA.length; i += 2) {
1706:                    String s = fmt.format(((Double) DATA[i]).doubleValue());
1707:                    if (!s.equals(DATA[i + 1])) {
1708:                        errln("FAIL: Got " + s + ", exp " + DATA[i + 1]);
1709:                    }
1710:                }
1711:            }
1712:
1713:            /**
1714:             * 4243011: Formatting .5 rounds to "1" instead of "0"
1715:             */
1716:            public void Test4243011() {
1717:                double DATA[] = { 0.5, 1.5, 2.5, 3.5, 4.5 };
1718:                String EXPECTED[] = { "0.", "2.", "2.", "4.", "4." };
1719:
1720:                DecimalFormat format = new DecimalFormat("0.");
1721:                for (int i = 0; i < DATA.length; i++) {
1722:                    String result = format.format(DATA[i]);
1723:                    if (result.equals(EXPECTED[i])) {
1724:                        logln("OK: got " + result);
1725:                    } else {
1726:                        errln("FAIL: got " + result);
1727:                    }
1728:                }
1729:            }
1730:
1731:            /**
1732:             * 4243108: format(0.0) gives "0.1" if preceded by parse("99.99")
1733:             */
1734:            public void Test4243108() {
1735:                DecimalFormat f = new DecimalFormat("#.#");
1736:                String result = f.format(0.0);
1737:                if (result.equals("0")) {
1738:                    logln("OK: got " + result);
1739:                } else {
1740:                    errln("FAIL: got " + result);
1741:                }
1742:                try {
1743:                    double dResult = f.parse("99.99").doubleValue();
1744:                    if (dResult == 99.99) {
1745:                        logln("OK: got " + dResult);
1746:                    } else {
1747:                        errln("FAIL: got " + dResult);
1748:                    }
1749:                } catch (ParseException e) {
1750:                    errln("Caught a ParseException:");
1751:                    e.printStackTrace();
1752:                }
1753:                result = f.format(0.0);
1754:                if (result.equals("0")) {
1755:                    logln("OK: got " + result);
1756:                } else {
1757:                    errln("FAIL: got " + result);
1758:                }
1759:            }
1760:
1761:            /**
1762:             * 4330377: DecimalFormat engineering notation gives incorrect results
1763:             */
1764:            public void test4330377() {
1765:                /*
1766:                double[] input = {5000.0, 500.0, 50.0, 5.0, 0.5, 0.05, 0.005, 0.0005,
1767:                       5050.0, 505.0, 50.5, 5.05, 0.505, 0.0505, 0.00505, 0.000505};
1768:                String[] pattern = {"000.#E0", "##0.#E0", "#00.#E0"};
1769:                String[][] expected = {
1770:                    // it's questionable whether "#00.#E0" should result in post-decimal
1771:                    // zeroes, i.e., whether "5.0E3", "5.0E0", "5.0E-3" are really good
1772:                    {"500E1", "5E3", "5.0E3"},
1773:                    {"500E0", "500E0", "500E0"},
1774:                    {"500E-1", "50E0", "50E0"},
1775:                    {"500E-2", "5E0", "5.0E0"},
1776:                    {"500E-3", "500E-3", "500E-3"},
1777:                    {"500E-4", "50E-3", "50E-3"},
1778:                    {"500E-5", "5E-3", "5.0E-3"},
1779:                    {"500E-6", "500E-6", "500E-6"},
1780:                    {"505E1", "5.05E3", "5.05E3"},
1781:                    {"505E0", "505E0", "505E0"},
1782:                    {"505E-1", "50.5E0", "50.5E0"},
1783:                    {"505E-2", "5.05E0", "5.05E0"},
1784:                    {"505E-3", "505E-3", "505E-3"},
1785:                    {"505E-4", "50.5E-3", "50.5E-3"},
1786:                    {"505E-5", "5.05E-3", "5.05E-3"},
1787:                    {"505E-6", "505E-6", "505E-6"}
1788:                };
1789:                for (int i = 0; i < input.length; i++) {
1790:                    for (int j = 0; j < pattern.length; j++) {
1791:                        DecimalFormat format = new DecimalFormat(pattern[j]);
1792:                        String result = format.format(input[i]);
1793:                        if (!result.equals(expected[i][j])) {
1794:                            errln("FAIL: input: " + input[i] +
1795:                                    ", pattern: " + pattern[j] +
1796:                                    ", expected: " + expected[i][j] +
1797:                                    ", got: " + result);
1798:                        }
1799:                    }
1800:                }
1801:                 */
1802:            }
1803:
1804:            /**
1805:             * 4233840: NumberFormat does not round correctly
1806:             */
1807:            public void test4233840() {
1808:                float f = 0.0099f;
1809:
1810:                NumberFormat nf = new DecimalFormat("0.##",
1811:                        new DecimalFormatSymbols(Locale.US));
1812:                nf.setMinimumFractionDigits(2);
1813:
1814:                String result = nf.format(f);
1815:
1816:                if (!result.equals("0.01")) {
1817:                    errln("FAIL: input: " + f + ", expected: 0.01, got: "
1818:                            + result);
1819:                }
1820:            }
1821:
1822:            /**
1823:             * 4241880: Decimal format doesnt round a double properly when the number is less than 1
1824:             */
1825:            public void test4241880() {
1826:                Locale savedLocale = Locale.getDefault();
1827:                Locale.setDefault(Locale.US);
1828:                double[] input = { .019, .009, .015, .016, .014, .004, .005,
1829:                        .006, .007, .008, .5, 1.5, .05, .15, .005, .015, .0005,
1830:                        .0015, };
1831:                String[] pattern = { "##0%", "##0%", "##0%", "##0%", "##0%",
1832:                        "##0%", "##0%", "##0%", "##0%", "##0%", "#,##0",
1833:                        "#,##0", "#,##0.0", "#,##0.0", "#,##0.00", "#,##0.00",
1834:                        "#,##0.000", "#,##0.000", };
1835:                String[] expected = { "2%", "1%", "2%", "2%", "1%", "0%", "0%",
1836:                        "1%", "1%", "1%", "0", "2", "0.0", "0.2", "0.00",
1837:                        "0.02", "0.000", "0.002", };
1838:                for (int i = 0; i < input.length; i++) {
1839:                    DecimalFormat format = new DecimalFormat(pattern[i]);
1840:                    String result = format.format(input[i]);
1841:                    if (!result.equals(expected[i])) {
1842:                        errln("FAIL: input: " + input[i] + ", pattern: "
1843:                                + pattern[i] + ", expected: " + expected[i]
1844:                                + ", got: " + result);
1845:                    }
1846:                }
1847:                Locale.setDefault(savedLocale);
1848:            }
1849:        }
1850:
1851:        class myformat implements  Serializable {
1852:            DateFormat _dateFormat = DateFormat.getDateInstance();
1853:
1854:            public String Now() {
1855:                GregorianCalendar calendar = new GregorianCalendar();
1856:                Date t = calendar.getTime();
1857:                String nowStr = _dateFormat.format(t);
1858:                return nowStr;
1859:            }
1860:        }
1861:
1862:        class MyNumberFormatTest extends NumberFormat {
1863:            public StringBuffer format(double number, StringBuffer toAppendTo,
1864:                    FieldPosition pos) {
1865:                return new StringBuffer("");
1866:            }
1867:
1868:            public StringBuffer format(long number, StringBuffer toAppendTo,
1869:                    FieldPosition pos) {
1870:                return new StringBuffer("");
1871:            }
1872:
1873:            public Number parse(String text, ParsePosition parsePosition) {
1874:                return new Integer(0);
1875:            }
1876:
1877:            public StringBuffer format(BigDecimal number,
1878:                    StringBuffer toAppendTo, FieldPosition pos) {
1879:                return new StringBuffer("");
1880:            }
1881:
1882:            public StringBuffer format(BigInteger number,
1883:                    StringBuffer toAppendTo, FieldPosition pos) {
1884:                return new StringBuffer("");
1885:            }
1886:
1887:            public StringBuffer format(com.ibm.icu.math.BigDecimal number,
1888:                    StringBuffer toAppendTo, FieldPosition pos) {
1889:                return new StringBuffer("");
1890:            }
1891:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.