Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/java/text/Format/NumberFormat/NumberRegression.java
47178 views
/*1* Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/**24* @test25* @bug 4052223 4059870 4061302 4062486 4066646 4068693 4070798 4071005 407101426* 4071492 4071859 4074454 4074620 4075713 4083018 4086575 4087244 408724527* 4087251 4087535 4088161 4088503 4090489 4090504 4092480 4092561 409571328* 4098741 4099404 4101481 4106658 4106662 4106664 4108738 4110936 412284029* 4125885 4134034 4134300 4140009 4141750 4145457 4147295 4147706 416219830* 4162852 4167494 4170798 4176114 4179818 4185761 4212072 4212073 421674231* 4217661 4243011 4243108 4330377 4233840 4241880 4833877 800857732* @summary Regression tests for NumberFormat and associated classes33* @library /java/text/testlib34* @build IntlTest HexDumpReader35* @modules java.base/sun.util.resources36* @compile -XDignore.symbol.file NumberRegression.java37* @run main/othervm -Djava.locale.providers=JRE,SPI NumberRegression38*/3940/*41(C) Copyright Taligent, Inc. 1996 - All Rights Reserved42(C) Copyright IBM Corp. 1996 - All Rights Reserved4344The original version of this source code and documentation is copyrighted and45owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These materials are46provided under terms of a License Agreement between Taligent and Sun. This47technology is protected by multiple US and International patents. This notice and48attribution to Taligent may not be removed.49Taligent is a registered trademark of Taligent, Inc.50*/5152import java.text.*;53import java.util.*;54import java.math.BigDecimal;55import java.io.*;56import java.math.BigInteger;57import sun.util.resources.LocaleData;5859public class NumberRegression extends IntlTest {6061public static void main(String[] args) throws Exception {62new NumberRegression().run(args);63}6465/**66* NumberFormat.equals comparing with null should always return false.67*/68public void Test4075713(){6970try {71MyNumberFormatTest tmp = new MyNumberFormatTest();72if (!tmp.equals(null))73logln("NumberFormat.equals passed");74} catch (NullPointerException e) {75errln("(new MyNumberFormatTest()).equals(null) throws unexpected exception");76}77}7879/**80* NumberFormat.equals comparing two obj equal even the setGroupingUsed81* flag is different.82*/83public void Test4074620() {8485MyNumberFormatTest nf1 = new MyNumberFormatTest();86MyNumberFormatTest nf2 = new MyNumberFormatTest();8788nf1.setGroupingUsed(false);89nf2.setGroupingUsed(true);9091if (nf1.equals(nf2)) errln("Test for bug 4074620 failed");92else logln("Test for bug 4074620 passed.");93return;94}959697/**98* DecimalFormat.format() incorrectly uses maxFractionDigits setting.99*/100101public void Test4088161 (){102DecimalFormat df = new DecimalFormat();103double d = 100;104df.setMinimumFractionDigits(0);105df.setMaximumFractionDigits(16);106StringBuffer sBuf1 = new StringBuffer("");107FieldPosition fp1 = new FieldPosition(0);108logln("d = " + d);109logln("maxFractionDigits = " + df.getMaximumFractionDigits());110logln(" format(d) = '" + df.format(d, sBuf1, fp1) + "'");111df.setMaximumFractionDigits(17);112StringBuffer sBuf2 = new StringBuffer("");113FieldPosition fp2 = new FieldPosition(0);114logln("maxFractionDigits = " + df.getMaximumFractionDigits());115df.format(d, sBuf2, fp2);116String expected = Locale.getDefault().equals(new Locale("hi", "IN")) ?117"\u0967\u0966\u0966" : "100";118if (!sBuf2.toString().equals(expected))119errln(" format(d) = '" + sBuf2 + "'");120}121/**122* DecimalFormatSymbols should be cloned in the ctor DecimalFormat.123* DecimalFormat(String, DecimalFormatSymbols).124*/125public void Test4087245 (){126DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance();127DecimalFormat df = new DecimalFormat("#,##0.0", symbols);128long n = 123;129StringBuffer buf1 = new StringBuffer();130StringBuffer buf2 = new StringBuffer();131logln("format(" + n + ") = " +132df.format(n, buf1, new FieldPosition(0)));133symbols.setDecimalSeparator('p'); // change value of field134logln("format(" + n + ") = " +135df.format(n, buf2, new FieldPosition(0)));136if (!buf1.toString().equals(buf2.toString()))137errln("Test for bug 4087245 failed");138}139/**140* DecimalFormat.format() incorrectly formats 0.0141*/142public void Test4087535 ()143{144DecimalFormat df = new DecimalFormat();145df.setMinimumIntegerDigits(0);146147double n = 0;148String buffer = new String();149buffer = df.format(n);150if (buffer.length() == 0)151errln(n + ": '" + buffer + "'");152n = 0.1;153buffer = df.format(n);154if (buffer.length() == 0)155errln(n + ": '" + buffer + "'");156}157158/**159* DecimalFormat.format fails when groupingSize is set to 0.160*/161public void Test4088503 (){162DecimalFormat df = new DecimalFormat();163df.setGroupingSize(0);164StringBuffer sBuf = new StringBuffer("");165FieldPosition fp = new FieldPosition(0);166try {167logln(df.format(123, sBuf, fp).toString());168} catch (Exception foo) {169errln("Test for bug 4088503 failed.");170}171172}173/**174* NumberFormat.getCurrencyInstance is wrong.175*/176public void Test4066646 () {177float returnfloat = 0.0f;178assignFloatValue(2.04f);179assignFloatValue(2.03f);180assignFloatValue(2.02f);181assignFloatValue(0.0f);182}183184public float assignFloatValue(float returnfloat)185{186logln(" VALUE " + returnfloat);187NumberFormat nfcommon = NumberFormat.getCurrencyInstance(Locale.US);188nfcommon.setGroupingUsed(false);189190String stringValue = nfcommon.format(returnfloat).substring(1);191if (Float.valueOf(stringValue).floatValue() != returnfloat)192errln(" DISPLAYVALUE " + stringValue);193return returnfloat;194} // End Of assignFloatValue()195196/**197* DecimalFormat throws exception when parsing "0"198*/199public void Test4059870() {200DecimalFormat format = new DecimalFormat("00");201try {202logln(format.parse("0").toString());203} catch (Exception e) { errln("Test for bug 4059870 failed : " + e); }204}205/**206* DecimalFormatSymbol.equals should always return false when207* comparing with null.208*/209210public void Test4083018 (){211DecimalFormatSymbols dfs = DecimalFormatSymbols.getInstance();212try {213if (!dfs.equals(null))214logln("Test Passed!");215} catch (Exception foo) {216errln("Test for bug 4083018 failed => Message : " + foo.getMessage());217}218}219/**220* DecimalFormat does not round up correctly.221*/222public void Test4071492 (){223Locale savedLocale = Locale.getDefault();224Locale.setDefault(Locale.US);225double x = 0.00159999;226NumberFormat nf = NumberFormat.getInstance();227nf.setMaximumFractionDigits(4);228String out = nf.format(x);229logln("0.00159999 formats with 4 fractional digits to " + out);230String expected = "0.0016";231if (!out.equals(expected))232errln("FAIL: Expected " + expected);233Locale.setDefault(savedLocale);234}235236/**237* A space as a group separator for localized pattern causes238* wrong format. WorkAround : use non-breaking space.239*/240public void Test4086575() {241242NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE);243logln("nf toPattern1: " + ((DecimalFormat)nf).toPattern());244logln("nf toLocPattern1: " + ((DecimalFormat)nf).toLocalizedPattern());245246// No group separator247logln("...applyLocalizedPattern ###,00;(###,00) ");248((DecimalFormat)nf).applyLocalizedPattern("###,00;(###,00)");249logln("nf toPattern2: " + ((DecimalFormat)nf).toPattern());250logln("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern());251252logln("nf: " + nf.format(1234)); // 1234,00253logln("nf: " + nf.format(-1234)); // (1234,00)254255// Space as group separator256257logln("...applyLocalizedPattern # ###,00;(# ###,00) ");258((DecimalFormat)nf).applyLocalizedPattern("#\u00a0###,00;(#\u00a0###,00)");259logln("nf toPattern2: " + ((DecimalFormat)nf).toPattern());260logln("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern());261String buffer = nf.format(1234);262if (!buffer.equals("1\u00a0234,00"))263errln("nf : " + buffer); // Expect 1 234,00264buffer = nf.format(-1234);265if (!buffer.equals("(1\u00a0234,00)"))266errln("nf : " + buffer); // Expect (1 234,00)267268// Erroneously prints:269// 1234,00 ,270// (1234,00 ,)271272}273/**274* DecimalFormat.parse returns wrong value275*/276public void Test4068693()277{278Locale savedLocale = Locale.getDefault();279Locale.setDefault(Locale.US);280logln("----- Test Application -----");281ParsePosition pos;282DecimalFormat df = new DecimalFormat();283Double d = (Double)df.parse("123.55456", pos=new ParsePosition(0));284if (!d.toString().equals("123.55456")) {285errln("Result -> " + d.doubleValue());286}287Locale.setDefault(savedLocale);288}289290/* bugs 4069754, 4067878291* null pointer thrown when accessing a deserialized DecimalFormat292* object.293*/294public void Test4069754()295{296try {297myformat it = new myformat();298logln(it.Now());299FileOutputStream ostream = new FileOutputStream("t.tmp");300ObjectOutputStream p = new ObjectOutputStream(ostream);301p.writeObject(it);302ostream.close();303logln("Saved ok.");304305FileInputStream istream = new FileInputStream("t.tmp");306ObjectInputStream p2 = new ObjectInputStream(istream);307myformat it2 = (myformat)p2.readObject();308logln(it2.Now());309istream.close();310logln("Loaded ok.");311} catch (Exception foo) {312errln("Test for bug 4069754 or 4057878 failed => Exception: " + foo.getMessage());313}314}315316/**317* DecimalFormat.applyPattern(String) allows illegal patterns318*/319public void Test4087251 (){320DecimalFormat df = new DecimalFormat();321try {322df.applyPattern("#.#.#");323logln("toPattern() returns \"" + df.toPattern() + "\"");324errln("applyPattern(\"#.#.#\") doesn't throw IllegalArgumentException");325} catch (IllegalArgumentException e) {326logln("Caught Illegal Argument Error !");327}328// Second test; added 5/11/98 when reported to fail on 1.2b3329try {330df.applyPattern("#0.0#0#0");331logln("toPattern() returns \"" + df.toPattern() + "\"");332errln("applyPattern(\"#0.0#0#0\") doesn't throw IllegalArgumentException");333} catch (IllegalArgumentException e) {334logln("Ok - IllegalArgumentException for #0.0#0#0");335}336}337338/**339* DecimalFormat.format() loses precision340*/341public void Test4090489 (){342Locale savedLocale = Locale.getDefault();343Locale.setDefault(Locale.US);344DecimalFormat df = new DecimalFormat();345df.setMinimumFractionDigits(10);346df.setGroupingUsed(false);347double d = 1.000000000000001E7;348BigDecimal bd = new BigDecimal(d);349StringBuffer sb = new StringBuffer("");350FieldPosition fp = new FieldPosition(0);351logln("d = " + d);352logln("BigDecimal.toString(): " + bd.toString());353df.format(d, sb, fp);354if (!sb.toString().equals("10000000.0000000100")) {355errln("DecimalFormat.format(): " + sb.toString());356}357Locale.setDefault(savedLocale);358}359360/**361* DecimalFormat.format() loses precision362*/363public void Test4090504 ()364{365double d = 1;366logln("d = " + d);367DecimalFormat df = new DecimalFormat();368StringBuffer sb;369FieldPosition fp;370try {371for (int i = 17; i <= 20; i++) {372df.setMaximumFractionDigits(i);373sb = new StringBuffer("");374fp = new FieldPosition(0);375logln(" getMaximumFractionDigits() = " + i);376logln(" formated: " + df.format(d, sb, fp));377}378} catch (Exception foo) {379errln("Bug 4090504 regression test failed. Message : " + foo.getMessage());380}381}382/**383* DecimalFormat.parse(String str, ParsePosition pp) loses precision384*/385public void Test4095713 ()386{387Locale savedLocale = Locale.getDefault();388Locale.setDefault(Locale.US);389DecimalFormat df = new DecimalFormat();390String str = "0.1234";391Double d1 = new Double(str);392Double d2 = (Double) df.parse(str, new ParsePosition(0));393logln(d1.toString());394if (d2.doubleValue() != d1.doubleValue())395errln("Bug 4095713 test failed, new double value : " + d2.doubleValue());396Locale.setDefault(savedLocale);397}398399/**400* DecimalFormat.parse() fails when multiplier is not set to 1401*/402public void Test4092561 ()403{404Locale savedLocale = Locale.getDefault();405Locale.setDefault(Locale.US);406DecimalFormat df = new DecimalFormat();407408String str = Long.toString(Long.MIN_VALUE);409logln("Long.MIN_VALUE : " + df.parse(str, new ParsePosition(0)).toString());410df.setMultiplier(100);411Number num = df.parse(str, new ParsePosition(0));412if (num.doubleValue() != -9.223372036854776E16) {413errln("Bug 4092561 test failed when multiplier is not set to 1. Expected: -9.223372036854776E16, got: " + num.doubleValue());414}415416df.setMultiplier(-100);417num = df.parse(str, new ParsePosition(0));418if (num.doubleValue() != 9.223372036854776E16) {419errln("Bug 4092561 test failed when multiplier is not set to 1. Expected: 9.223372036854776E16, got: " + num.doubleValue());420}421422str = Long.toString(Long.MAX_VALUE);423logln("Long.MAX_VALUE : " + df.parse(str, new ParsePosition(0)).toString());424425df.setMultiplier(100);426num = df.parse(str, new ParsePosition(0));427if (num.doubleValue() != 9.223372036854776E16) {428errln("Bug 4092561 test failed when multiplier is not set to 1. Expected: 9.223372036854776E16, got: " + num.doubleValue());429}430431df.setMultiplier(-100);432num = df.parse(str, new ParsePosition(0));433if (num.doubleValue() != -9.223372036854776E16) {434errln("Bug 4092561 test failed when multiplier is not set to 1. Expected: -9.223372036854776E16, got: " + num.doubleValue());435}436437Locale.setDefault(savedLocale);438}439440/**441* DecimalFormat: Negative format ignored.442*/443public void Test4092480 ()444{445DecimalFormat dfFoo = new DecimalFormat("000");446447try {448dfFoo.applyPattern("0000;-000");449if (!dfFoo.toPattern().equals("#0000"))450errln("dfFoo.toPattern : " + dfFoo.toPattern());451logln(dfFoo.format(42));452logln(dfFoo.format(-42));453dfFoo.applyPattern("000;-000");454if (!dfFoo.toPattern().equals("#000"))455errln("dfFoo.toPattern : " + dfFoo.toPattern());456logln(dfFoo.format(42));457logln(dfFoo.format(-42));458459dfFoo.applyPattern("000;-0000");460if (!dfFoo.toPattern().equals("#000"))461errln("dfFoo.toPattern : " + dfFoo.toPattern());462logln(dfFoo.format(42));463logln(dfFoo.format(-42));464465dfFoo.applyPattern("0000;-000");466if (!dfFoo.toPattern().equals("#0000"))467errln("dfFoo.toPattern : " + dfFoo.toPattern());468logln(dfFoo.format(42));469logln(dfFoo.format(-42));470} catch (Exception foo) {471errln("Message " + foo.getMessage());472}473}474/**475* NumberFormat.getCurrencyInstance() produces format that uses476* decimal separator instead of monetary decimal separator.477*478* Rewrote this test not to depend on the actual pattern. Pattern should479* never contain the monetary separator! Decimal separator in pattern is480* interpreted as monetary separator if currency symbol is seen!481*/482public void Test4087244 () {483Locale de = new Locale("pt", "PT");484DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(de);485DecimalFormatSymbols sym = df.getDecimalFormatSymbols();486sym.setMonetaryDecimalSeparator('$');487df.setDecimalFormatSymbols(sym);488char decSep = sym.getDecimalSeparator();489char monSep = sym.getMonetaryDecimalSeparator();490char zero = sym.getZeroDigit();491if (decSep == monSep) {492errln("ERROR in test: want decimal sep != monetary sep");493} else {494df.setMinimumIntegerDigits(1);495df.setMinimumFractionDigits(2);496String str = df.format(1.23);497String monStr = "1" + monSep + "23";498String decStr = "1" + decSep + "23";499if (str.indexOf(monStr) >= 0 && str.indexOf(decStr) < 0) {500logln("OK: 1.23 -> \"" + str + "\" contains \"" +501monStr + "\" and not \"" + decStr + '"');502} else {503errln("FAIL: 1.23 -> \"" + str + "\", should contain \"" +504monStr +505"\" and not \"" + decStr + '"');506}507}508}509/**510* Number format data rounding errors for locale FR511*/512public void Test4070798 () {513NumberFormat formatter;514String tempString;515/* User error :516String expectedDefault = "-5\u00a0789,987";517String expectedCurrency = "5\u00a0789,98 F";518String expectedPercent = "-578\u00a0998%";519*/520String expectedDefault = "-5\u00a0789,988";521String expectedCurrency = "5\u00a0789,99 \u20AC";522// changed for bug 6547501523String expectedPercent = "-578\u00a0999 %";524525formatter = NumberFormat.getNumberInstance(Locale.FRANCE);526tempString = formatter.format (-5789.9876);527528if (tempString.equals(expectedDefault)) {529logln ("Bug 4070798 default test passed.");530} else {531errln("Failed:" +532" Expected " + expectedDefault +533" Received " + tempString );534}535536537formatter = NumberFormat.getCurrencyInstance(Locale.FRANCE);538tempString = formatter.format( 5789.9876 );539540if (tempString.equals(expectedCurrency) ) {541logln ("Bug 4070798 currency test assed.");542} else {543errln("Failed:" +544" Expected " + expectedCurrency +545" Received " + tempString );546}547548549formatter = NumberFormat.getPercentInstance(Locale.FRANCE);550tempString = formatter.format (-5789.9876);551552if (tempString.equals(expectedPercent) ) {553logln ("Bug 4070798 percentage test passed.");554} else {555errln("Failed:" +556" Expected " + expectedPercent +557" Received " + tempString );558}559}560/**561* Data rounding errors for French (Canada) locale562*/563public void Test4071005 () {564565NumberFormat formatter;566String tempString;567/* user error :568String expectedDefault = "-5 789,987";569String expectedCurrency = "5 789,98 $";570String expectedPercent = "-578 998%";571*/572String expectedDefault = "-5\u00a0789,988";573String expectedCurrency = "5\u00a0789,99 $";574// changed for bug 6547501575String expectedPercent = "-578\u00a0999 %";576577formatter = NumberFormat.getNumberInstance(Locale.CANADA_FRENCH);578tempString = formatter.format (-5789.9876);579if (tempString.equals(expectedDefault)) {580logln ("Bug 4071005 default test passed.");581} else {582errln("Failed:" +583" Expected " + expectedDefault +584" Received " + tempString );585}586587formatter = NumberFormat.getCurrencyInstance(Locale.CANADA_FRENCH);588tempString = formatter.format( 5789.9876 ) ;589590if (tempString.equals(expectedCurrency) ) {591logln ("Bug 4071005 currency test passed.");592} else {593errln("Failed:" +594" Expected " + expectedCurrency +595" Received " + tempString );596}597formatter = NumberFormat.getPercentInstance(Locale.CANADA_FRENCH);598tempString = formatter.format (-5789.9876);599600if (tempString.equals(expectedPercent) ) {601logln ("Bug 4071005 percentage test passed.");602} else {603errln("Failed:" +604" Expected " + expectedPercent +605" Received " + tempString );606}607}608609/**610* Data rounding errors for German (Germany) locale611*/612public void Test4071014 () {613NumberFormat formatter;614String tempString;615/* user error :616String expectedDefault = "-5.789,987";617String expectedCurrency = "5.789,98 DM";618String expectedPercent = "-578.998%";619*/620String expectedDefault = "-5.789,988";621String expectedCurrency = "5.789,99 \u20AC";622String expectedPercent = "-578.999%";623624formatter = NumberFormat.getNumberInstance(Locale.GERMANY);625tempString = formatter.format (-5789.9876);626627if (tempString.equals(expectedDefault)) {628logln ("Bug 4071014 default test passed.");629} else {630errln("Failed:" +631" Expected " + expectedDefault +632" Received " + tempString );633}634635formatter = NumberFormat.getCurrencyInstance(Locale.GERMANY);636tempString = formatter.format( 5789.9876 ) ;637638if (tempString.equals(expectedCurrency) ) {639logln ("Bug 4071014 currency test passed.");640} else {641errln("Failed:" +642" Expected " + expectedCurrency +643" Received " + tempString );644}645646formatter = NumberFormat.getPercentInstance(Locale.GERMANY);647tempString = formatter.format (-5789.9876);648649if (tempString.equals(expectedPercent) ) {650logln ("Bug 4071014 percentage test passed.");651} else {652errln("Failed:" +653" Expected " + expectedPercent +654" Received " + tempString );655}656657}658/**659* Data rounding errors for Italian locale number formats660*/661public void Test4071859 () {662NumberFormat formatter;663String tempString;664/* user error :665String expectedDefault = "-5.789,987";666String expectedCurrency = "-L. 5.789,98";667String expectedPercent = "-578.998%";668*/669String expectedDefault = "-5.789,988";670String expectedCurrency = "-\u20AC 5.789,99";671String expectedPercent = "-578.999%";672673formatter = NumberFormat.getNumberInstance(Locale.ITALY);674tempString = formatter.format (-5789.9876);675676if (tempString.equals(expectedDefault)) {677logln ("Bug 4071859 default test passed.");678} else {679errln("Failed:" +680" Expected " + expectedDefault +681" Received " + tempString );682}683684formatter = NumberFormat.getCurrencyInstance(Locale.ITALY);685tempString = formatter.format( -5789.9876 ) ;686687if (tempString.equals(expectedCurrency) ) {688logln ("Bug 4071859 currency test passed.");689} else {690errln("Failed:" +691" Expected " + expectedCurrency +692" Received " + tempString );693}694695formatter = NumberFormat.getPercentInstance(Locale.ITALY);696tempString = formatter.format (-5789.9876);697698if (tempString.equals(expectedPercent) ) {699logln ("Bug 4071859 percentage test passed.");700} else {701errln("Failed:" +702" Expected " + expectedPercent +703" Received " + tempString );704}705706}707708/* bug 4071859709* Test rounding for nearest even.710*/711public void Test4093610()712{713Locale savedLocale = Locale.getDefault();714Locale.setDefault(Locale.US);715DecimalFormat df = new DecimalFormat("#0.#");716717roundingTest(df, 12.15, "12.2"); // Rounding-up. Above tie (12.150..)718roundingTest(df, 12.25, "12.2"); // No round-up. Exact + half-even rule.719roundingTest(df, 12.45, "12.4"); // No round-up. Below tie (12.449..)720roundingTest(df, 12.450000001,"12.5"); // Rounding-up. Above tie.721roundingTest(df, 12.55, "12.6"); // Rounding-up. Above tie (12.550..)722roundingTest(df, 12.650000001,"12.7"); // Rounding-up. Above tie.723roundingTest(df, 12.75, "12.8"); // Rounding-up. Exact + half-even rule.724roundingTest(df, 12.750000001,"12.8"); // Rounding-up. Above tie.725roundingTest(df, 12.85, "12.8"); // No round-up. Below tie (12.849..)726roundingTest(df, 12.850000001,"12.9"); // Rounding-up. Above tie.727roundingTest(df, 12.950000001,"13"); // Rounding-up. Above tie.728729Locale.setDefault(savedLocale);730}731732void roundingTest(DecimalFormat df, double x, String expected)733{734String out = df.format(x);735logln("" + x + " formats with 1 fractional digits to " + out);736if (!out.equals(expected)) errln("FAIL: Expected " + expected);737}738/**739* Tests the setMaximumFractionDigits limit.740*/741public void Test4098741()742{743try {744NumberFormat fmt = NumberFormat.getPercentInstance();745fmt.setMaximumFractionDigits(20);746logln(fmt.format(.001));747} catch (Exception foo) {748errln("Bug 4098471 failed with exception thrown : " + foo.getMessage());749}750}751/**752* Tests illegal pattern exception.753* Fix comment : HShih A31 Part1 will not be fixed and javadoc needs to be updated.754* Part2 has been fixed.755*/756public void Test4074454()757{758Locale savedLocale = Locale.getDefault();759Locale.setDefault(Locale.US);760try {761DecimalFormat fmt = new DecimalFormat("#,#00.00;-#.#");762logln("Inconsistent negative pattern is fine.");763DecimalFormat newFmt = new DecimalFormat("#,#00.00 p''ieces;-#,#00.00 p''ieces");764String tempString = newFmt.format(3456.78);765if (!tempString.equals("3,456.78 p'ieces"))766errln("Failed! 3,456.78 p'ieces expected, but got : " + tempString);767} catch (Exception foo) {768errln("An exception was thrown for any inconsistent negative pattern.");769}770Locale.setDefault(savedLocale);771}772773/**774* Tests all different comments.775* Response to some comments :776* [1] DecimalFormat.parse API documentation is more than just one line.777* This is not a reproducable doc error in 116 source code.778* [2] See updated javadoc.779* [3] Fixed.780* [4] NumberFormat.parse(String, ParsePosition) : If parsing fails,781* a null object will be returned. The unchanged parse position also782* reflects an error.783* NumberFormat.parse(String) : If parsing fails, an ParseException784* will be thrown.785* See updated javadoc for more details.786* [5] See updated javadoc.787* [6] See updated javadoc.788* [7] This is a correct behavior if the DateFormat object is linient.789* Otherwise, an IllegalArgumentException will be thrown when formatting790* "January 35". See GregorianCalendar class javadoc for more details.791*/792public void Test4099404()793{794try {795DecimalFormat fmt = new DecimalFormat("000.0#0");796errln("Bug 4099404 failed applying illegal pattern \"000.0#0\"");797} catch (Exception foo) {798logln("Bug 4099404 pattern \"000.0#0\" passed");799}800try {801DecimalFormat fmt = new DecimalFormat("0#0.000");802errln("Bug 4099404 failed applying illegal pattern \"0#0.000\"");803} catch (Exception foo) {804logln("Bug 4099404 pattern \"0#0.000\" passed");805}806}807/**808* DecimalFormat.applyPattern doesn't set minimum integer digits809*/810public void Test4101481()811{812DecimalFormat sdf = new DecimalFormat("#,##0");813if (sdf.getMinimumIntegerDigits() != 1)814errln("Minimum integer digits : " + sdf.getMinimumIntegerDigits());815}816/**817* Tests ParsePosition.setErrorPosition() and ParsePosition.getErrorPosition().818*/819public void Test4052223()820{821try {822DecimalFormat fmt = new DecimalFormat("#,#00.00");823Number num = fmt.parse("abc3");824errln("Bug 4052223 failed : can't parse string \"a\". Got " + num);825} catch (ParseException foo) {826logln("Caught expected ParseException : " + foo.getMessage() + " at index : " + foo.getErrorOffset());827}828}829/**830* API tests for API addition request A9.831*/832public void Test4061302()833{834DecimalFormatSymbols fmt = DecimalFormatSymbols.getInstance();835String currency = fmt.getCurrencySymbol();836String intlCurrency = fmt.getInternationalCurrencySymbol();837char monDecSeparator = fmt.getMonetaryDecimalSeparator();838if (currency.equals("") ||839intlCurrency.equals("") ||840monDecSeparator == 0) {841errln("getCurrencySymbols failed, got empty string.");842}843logln("Before set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator);844fmt.setCurrencySymbol("XYZ");845fmt.setInternationalCurrencySymbol("ABC");846fmt.setMonetaryDecimalSeparator('*');847currency = fmt.getCurrencySymbol();848intlCurrency = fmt.getInternationalCurrencySymbol();849monDecSeparator = fmt.getMonetaryDecimalSeparator();850if (!currency.equals("XYZ") ||851!intlCurrency.equals("ABC") ||852monDecSeparator != '*') {853errln("setCurrencySymbols failed.");854}855logln("After set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator);856}857/**858* API tests for API addition request A23. FieldPosition.getBeginIndex and859* FieldPosition.getEndIndex.860*/861public void Test4062486()862{863DecimalFormat fmt = new DecimalFormat("#,##0.00");864StringBuffer formatted = new StringBuffer();865FieldPosition field = new FieldPosition(0);866Double num = new Double(1234.5);867fmt.format(num, formatted, field);868if (field.getBeginIndex() != 0 && field.getEndIndex() != 5)869errln("Format 1234.5 failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex());870field.setBeginIndex(7);871field.setEndIndex(4);872if (field.getBeginIndex() != 7 && field.getEndIndex() != 4)873errln("Set begin/end field indexes failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex());874}875876/**877* DecimalFormat.parse incorrectly works with a group separator.878*/879public void Test4108738()880{881882DecimalFormat df = new DecimalFormat("#,##0.###",883DecimalFormatSymbols.getInstance(java.util.Locale.US));884String text = "1.222,111";885Number num = df.parse(text,new ParsePosition(0));886if (!num.toString().equals("1.222"))887errln("\"" + text + "\" is parsed as " + num);888text = "1.222x111";889num = df.parse(text,new ParsePosition(0));890if (!num.toString().equals("1.222"))891errln("\"" + text + "\" is parsed as " + num);892}893894/**895* DecimalFormat.format() incorrectly formats negative doubles.896*/897public void Test4106658()898{899Locale savedLocale = Locale.getDefault();900Locale.setDefault(Locale.US);901DecimalFormat df = new DecimalFormat(); // Corrected; see 4147706902double d1 = -0.0;903double d2 = -0.0001;904StringBuffer buffer = new StringBuffer();905logln("pattern: \"" + df.toPattern() + "\"");906df.format(d1, buffer, new FieldPosition(0));907if (!buffer.toString().equals("-0")) { // Corrected; see 4147706908errln(d1 + " is formatted as " + buffer);909}910buffer.setLength(0);911df.format(d2, buffer, new FieldPosition(0));912if (!buffer.toString().equals("-0")) { // Corrected; see 4147706913errln(d2 + " is formatted as " + buffer);914}915Locale.setDefault(savedLocale);916}917918/**919* DecimalFormat.parse returns 0 if string parameter is incorrect.920*/921public void Test4106662()922{923DecimalFormat df = new DecimalFormat();924String text = "x";925ParsePosition pos1 = new ParsePosition(0), pos2 = new ParsePosition(0);926927logln("pattern: \"" + df.toPattern() + "\"");928Number num = df.parse(text, pos1);929if (num != null) {930errln("Test Failed: \"" + text + "\" is parsed as " + num);931}932df = null;933df = new DecimalFormat("$###.00");934num = df.parse("$", pos2);935if (num != null){936errln("Test Failed: \"$\" is parsed as " + num);937}938}939940/**941* NumberFormat.parse doesn't return null942*/943public void Test4114639()944{945NumberFormat format = NumberFormat.getInstance();946String text = "time 10:x";947ParsePosition pos = new ParsePosition(8);948Number result = format.parse(text, pos);949if (result != null) errln("Should return null but got : " + result); // Should be null; it isn't950}951952/**953* DecimalFormat.format(long n) fails if n * multiplier > MAX_LONG.954*/955public void Test4106664()956{957DecimalFormat df = new DecimalFormat();958long n = 1234567890123456L;959int m = 12345678;960BigInteger bigN = BigInteger.valueOf(n);961bigN = bigN.multiply(BigInteger.valueOf(m));962df.setMultiplier(m);963df.setGroupingUsed(false);964logln("formated: " +965df.format(n, new StringBuffer(), new FieldPosition(0)));966logln("expected: " + bigN.toString());967}968/**969* DecimalFormat.format incorrectly formats -0.0.970*/971public void Test4106667()972{973Locale savedLocale = Locale.getDefault();974Locale.setDefault(Locale.US);975DecimalFormat df = new DecimalFormat();976df.setPositivePrefix("+");977double d = -0.0;978logln("pattern: \"" + df.toPattern() + "\"");979StringBuffer buffer = new StringBuffer();980df.format(d, buffer, new FieldPosition(0));981if (!buffer.toString().equals("-0")) { // Corrected; see 4147706982errln(d + " is formatted as " + buffer);983}984Locale.setDefault(savedLocale);985}986987/**988* DecimalFormat.setMaximumIntegerDigits() works incorrectly.989*/990public void Test4110936()991{992NumberFormat nf = NumberFormat.getInstance();993nf.setMaximumIntegerDigits(128);994logln("setMaximumIntegerDigits(128)");995if (nf.getMaximumIntegerDigits() != 128)996errln("getMaximumIntegerDigits() returns " +997nf.getMaximumIntegerDigits());998}9991000/**1001* Locale data should use generic currency symbol1002*1003* 1) Make sure that all currency formats use the generic currency symbol.1004* 2) Make sure we get the same results using the generic symbol or a1005* hard-coded one.1006*/1007public void Test4122840()1008{1009Locale[] locales = NumberFormat.getAvailableLocales();10101011for (int i = 0; i < locales.length; i++) {1012ResourceBundle rb = LocaleData.getBundle("sun.text.resources.FormatData",1013locales[i]);1014//1015// Get the currency pattern for this locale. We have to fish it1016// out of the ResourceBundle directly, since DecimalFormat.toPattern1017// will return the localized symbol, not \00a41018//1019String[] numPatterns = (String[])rb.getObject("NumberPatterns");1020String pattern = numPatterns[1];10211022if (pattern.indexOf("\u00A4") == -1 ) {1023errln("Currency format for " + locales[i] +1024" does not contain generic currency symbol:" +1025pattern );1026}10271028// Create a DecimalFormat using the pattern we got and format a number1029DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locales[i]);1030DecimalFormat fmt1 = new DecimalFormat(pattern, symbols);10311032String result1 = fmt1.format(1.111);10331034//1035// Now substitute in the locale's currency symbol and create another1036// pattern. Replace the decimal separator with the monetary separator.1037//1038char decSep = symbols.getDecimalSeparator();1039char monSep = symbols.getMonetaryDecimalSeparator();1040StringBuffer buf = new StringBuffer(pattern);1041for (int j = 0; j < buf.length(); j++) {1042if (buf.charAt(j) == '\u00a4') {1043String cur = "'" + symbols.getCurrencySymbol() + "'";1044buf.replace(j, j+1, cur);1045j += cur.length() - 1;1046}1047}1048symbols.setDecimalSeparator(monSep);1049DecimalFormat fmt2 = new DecimalFormat(buf.toString(), symbols);10501051String result2 = fmt2.format(1.111);10521053if (!result1.equals(result2)) {1054errln("Results for " + locales[i] + " differ: " +1055result1 + " vs " + result2);1056}1057}1058}10591060/**1061* DecimalFormat.format() delivers wrong string.1062*/1063public void Test4125885()1064{1065Locale savedLocale = Locale.getDefault();1066Locale.setDefault(Locale.US);1067double rate = 12.34;1068DecimalFormat formatDec = new DecimalFormat ("000.00");1069logln("toPattern: " + formatDec.toPattern());1070String rateString= formatDec.format(rate);1071if (!rateString.equals("012.34"))1072errln("result : " + rateString + " expected : 012.34");1073rate = 0.1234;1074formatDec = null;1075formatDec = new DecimalFormat ("+000.00%;-000.00%");1076logln("toPattern: " + formatDec.toPattern());1077rateString= formatDec.format(rate);1078if (!rateString.equals("+012.34%"))1079errln("result : " + rateString + " expected : +012.34%");1080Locale.setDefault(savedLocale);1081}10821083/**1084**1085* DecimalFormat produces extra zeros when formatting numbers.1086*/1087public void Test4134034() {1088Locale savedLocale = Locale.getDefault();1089Locale.setDefault(Locale.US);1090DecimalFormat nf = new DecimalFormat("##,###,###.00");10911092String f = nf.format(9.02);1093if (f.equals("9.02")) logln(f + " ok"); else errln("9.02 -> " + f + "; want 9.02");10941095f = nf.format(0);1096if (f.equals(".00")) logln(f + " ok"); else errln("0 -> " + f + "; want .00");1097Locale.setDefault(savedLocale);1098}10991100/**1101* CANNOT REPRODUCE - This bug could not be reproduced. It may be1102* a duplicate of 4134034.1103*1104* JDK 1.1.6 Bug, did NOT occur in 1.1.51105* Possibly related to bug 4125885.1106*1107* This class demonstrates a regression in version 1.1.61108* of DecimalFormat class.1109*1110* 1.1.6 Results1111* Value 1.2 Format #.00 Result '01.20' !!!wrong1112* Value 1.2 Format 0.00 Result '001.20' !!!wrong1113* Value 1.2 Format 00.00 Result '0001.20' !!!wrong1114* Value 1.2 Format #0.0# Result '1.2'1115* Value 1.2 Format #0.00 Result '001.20' !!!wrong1116*1117* 1.1.5 Results1118* Value 1.2 Format #.00 Result '1.20'1119* Value 1.2 Format 0.00 Result '1.20'1120* Value 1.2 Format 00.00 Result '01.20'1121* Value 1.2 Format #0.0# Result '1.2'1122* Value 1.2 Format #0.00 Result '1.20'1123*/1124public void Test4134300() {1125Locale savedLocale = Locale.getDefault();1126Locale.setDefault(Locale.US);1127String[] DATA = {1128// Pattern Expected string1129"#.00", "1.20",1130"0.00", "1.20",1131"00.00", "01.20",1132"#0.0#", "1.2",1133"#0.00", "1.20",1134};1135for (int i=0; i<DATA.length; i+=2) {1136String result = new DecimalFormat(DATA[i]).format(1.2);1137if (!result.equals(DATA[i+1])) {1138errln("Fail: 1.2 x " + DATA[i] + " = " + result +1139"; want " + DATA[i+1]);1140}1141else {1142logln("Ok: 1.2 x " + DATA[i] + " = " + result);1143}1144}1145Locale.setDefault(savedLocale);1146}11471148/**1149* Empty pattern produces double negative prefix.1150*/1151public void Test4140009() {1152for (int i=0; i<2; ++i) {1153DecimalFormat f = null;1154switch (i) {1155case 0:1156f = new DecimalFormat("",1157DecimalFormatSymbols.getInstance(Locale.ENGLISH));1158break;1159case 1:1160f = new DecimalFormat("#.#",1161DecimalFormatSymbols.getInstance(Locale.ENGLISH));1162f.applyPattern("");1163break;1164}1165String s = f.format(123.456);1166if (!s.equals("123.456"))1167errln("Fail: Format empty pattern x 123.456 => " + s);1168s = f.format(-123.456);1169if (!s.equals("-123.456"))1170errln("Fail: Format empty pattern x -123.456 => " + s);1171}1172}11731174/**1175* BigDecimal numbers get their fractions truncated by NumberFormat.1176*/1177public void Test4141750() {1178try {1179String str = "12345.67";1180BigDecimal bd = new BigDecimal(str);1181NumberFormat nf = NumberFormat.getInstance(Locale.US);1182String sd = nf.format(bd);1183if (!sd.endsWith("67")) {1184errln("Fail: " + str + " x format -> " + sd);1185}1186}1187catch (Exception e) {1188errln(e.toString());1189e.printStackTrace();1190}1191}11921193/**1194* DecimalFormat toPattern() doesn't quote special characters or handle1195* single quotes.1196*/1197public void Test4145457() {1198try {1199DecimalFormat nf = (DecimalFormat)NumberFormat.getInstance();1200DecimalFormatSymbols sym = nf.getDecimalFormatSymbols();1201sym.setDecimalSeparator('\'');1202nf.setDecimalFormatSymbols(sym);1203double pi = 3.14159;12041205String[] PATS = { "#.00 'num''ber'", "''#.00''" };12061207for (int i=0; i<PATS.length; ++i) {1208nf.applyPattern(PATS[i]);1209String out = nf.format(pi);1210String pat = nf.toPattern();1211double val = nf.parse(out).doubleValue();12121213nf.applyPattern(pat);1214String out2 = nf.format(pi);1215String pat2 = nf.toPattern();1216double val2 = nf.parse(out2).doubleValue();12171218if (!pat.equals(pat2))1219errln("Fail with \"" + PATS[i] + "\": Patterns should concur, \"" +1220pat + "\" vs. \"" + pat2 + "\"");1221else1222logln("Ok \"" + PATS[i] + "\" toPattern() -> \"" + pat + '"');12231224if (val == val2 && out.equals(out2)) {1225logln("Ok " + pi + " x \"" + PATS[i] + "\" -> \"" +1226out + "\" -> " + val + " -> \"" +1227out2 + "\" -> " + val2);1228}1229else {1230errln("Fail " + pi + " x \"" + PATS[i] + "\" -> \"" +1231out + "\" -> " + val + " -> \"" +1232out2 + "\" -> " + val2);1233}1234}1235}1236catch (ParseException e) {1237errln("Fail: " + e);1238e.printStackTrace();1239}1240}12411242/**1243* DecimalFormat.applyPattern() sets minimum integer digits incorrectly.1244* CANNOT REPRODUCE1245* This bug is a duplicate of 4139344, which is a duplicate of 41343001246*/1247public void Test4147295() {1248DecimalFormat sdf = new DecimalFormat();1249String pattern = "#,###";1250logln("Applying pattern \"" + pattern + "\"");1251sdf.applyPattern(pattern);1252int minIntDig = sdf.getMinimumIntegerDigits();1253if (minIntDig != 0) {1254errln("Test failed");1255errln(" Minimum integer digits : " + minIntDig);1256errln(" new pattern: " + sdf.toPattern());1257} else {1258logln("Test passed");1259logln(" Minimum integer digits : " + minIntDig);1260}1261}12621263/**1264* DecimalFormat formats -0.0 as +0.01265* See also older related bug 4106658, 41066671266*/1267public void Test4147706() {1268DecimalFormat df = new DecimalFormat("#,##0.0##");1269df.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ENGLISH));1270double d1 = -0.0;1271double d2 = -0.0001;1272StringBuffer f1 = df.format(d1, new StringBuffer(), new FieldPosition(0));1273StringBuffer f2 = df.format(d2, new StringBuffer(), new FieldPosition(0));1274if (!f1.toString().equals("-0.0")) {1275errln(d1 + " x \"" + df.toPattern() + "\" is formatted as \"" + f1 + '"');1276}1277if (!f2.toString().equals("-0.0")) {1278errln(d2 + " x \"" + df.toPattern() + "\" is formatted as \"" + f2 + '"');1279}1280}12811282/**1283* NumberFormat cannot format Double.MAX_VALUE1284*/1285public void Test4162198() {1286double dbl = Double.MAX_VALUE;1287NumberFormat f = NumberFormat.getInstance();1288f.setMaximumFractionDigits(Integer.MAX_VALUE);1289f.setMaximumIntegerDigits(Integer.MAX_VALUE);1290String s = f.format(dbl);1291logln("The number " + dbl + " formatted to " + s);1292Number n = null;1293try {1294n = f.parse(s);1295} catch (java.text.ParseException e) {1296errln("Caught a ParseException:");1297e.printStackTrace();1298}1299logln("The string " + s + " parsed as " + n);1300if (n.doubleValue() != dbl) {1301errln("Round trip failure");1302}1303}13041305/**1306* NumberFormat does not parse negative zero.1307*/1308public void Test4162852() throws ParseException {1309for (int i=0; i<2; ++i) {1310NumberFormat f = (i == 0) ? NumberFormat.getInstance()1311: NumberFormat.getPercentInstance();1312double d = -0.0;1313String s = f.format(d);1314double e = f.parse(s).doubleValue();1315logln("" +1316d + " -> " +1317'"' + s + '"' + " -> " +1318e);1319if (e != 0.0 || 1.0/e > 0.0) {1320logln("Failed to parse negative zero");1321}1322}1323}13241325/**1326* NumberFormat truncates data1327*/1328public void Test4167494() throws Exception {1329NumberFormat fmt = NumberFormat.getInstance(Locale.US);13301331double a = Double.MAX_VALUE;1332String s = fmt.format(a);1333double b = fmt.parse(s).doubleValue();1334boolean match = a == b;1335if (match) {1336logln("" + a + " -> \"" + s + "\" -> " + b + " ok");1337} else {1338errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL");1339}13401341// We don't test Double.MIN_VALUE because the locale data for the US1342// currently doesn't specify enough digits to display Double.MIN_VALUE.1343// This is correct for now; however, we leave this here as a reminder1344// in case we want to address this later.1345if (false) {1346a = Double.MIN_VALUE;1347s = fmt.format(a);1348b = fmt.parse(s).doubleValue();1349match = a == b;1350if (match) {1351logln("" + a + " -> \"" + s + "\" -> " + b + " ok");1352} else {1353errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL");1354}1355}1356}13571358/**1359* DecimalFormat.parse() fails when ParseIntegerOnly set to true1360*/1361public void Test4170798() {1362Locale savedLocale = Locale.getDefault();1363Locale.setDefault(Locale.US);1364DecimalFormat df = new DecimalFormat();1365df.setParseIntegerOnly(true);1366Number n = df.parse("-0.0", new ParsePosition(0));1367if (!(n instanceof Long || n instanceof Integer)1368|| n.intValue() != 0) {1369errln("FAIL: parse(\"-0.0\") returns " +1370n + " (" + n.getClass().getName() + ')');1371}1372Locale.setDefault(savedLocale);1373}13741375/**1376* toPattern only puts the first grouping separator in.1377*/1378public void Test4176114() {1379String[] DATA = {1380"00", "#00",1381"000", "#000", // No grouping1382"#000", "#000", // No grouping1383"#,##0", "#,##0",1384"#,000", "#,000",1385"0,000", "#0,000",1386"00,000", "#00,000",1387"000,000", "#,000,000",1388"0,000,000,000,000.0000", "#0,000,000,000,000.0000", // Reported1389};1390for (int i=0; i<DATA.length; i+=2) {1391DecimalFormat df = new DecimalFormat(DATA[i]);1392String s = df.toPattern();1393if (!s.equals(DATA[i+1])) {1394errln("FAIL: " + DATA[i] + " -> " + s + ", want " + DATA[i+1]);1395}1396}1397}13981399/**1400* DecimalFormat is incorrectly rounding numbers like 1.2501 to 1.21401*/1402public void Test4179818() {1403String DATA[] = {1404// Input Pattern Expected output1405"1.2511", "#.#", "1.3",1406"1.2501", "#.#", "1.3",1407"0.9999", "#", "1",1408};1409DecimalFormat fmt = new DecimalFormat("#",1410DecimalFormatSymbols.getInstance(Locale.US));1411for (int i=0; i<DATA.length; i+=3) {1412double in = Double.valueOf(DATA[i]).doubleValue();1413String pat = DATA[i+1];1414String exp = DATA[i+2];1415fmt.applyPattern(pat);1416String out = fmt.format(in);1417if (out.equals(exp)) {1418logln("Ok: " + in + " x " + pat + " = " + out);1419} else {1420errln("FAIL: " + in + " x " + pat + " = " + out +1421", expected " + exp);1422}1423}1424}14251426public void Test4185761() throws IOException, ClassNotFoundException {1427/* Code used to write out the initial files, which are1428* then edited manually:1429NumberFormat nf = NumberFormat.getInstance(Locale.US);1430nf.setMinimumIntegerDigits(0x111); // Keep under 3091431nf.setMaximumIntegerDigits(0x112); // Keep under 3091432nf.setMinimumFractionDigits(0x113); // Keep under 3401433nf.setMaximumFractionDigits(0x114); // Keep under 3401434FileOutputStream ostream =1435new FileOutputStream("NumberFormat4185761");1436ObjectOutputStream p = new ObjectOutputStream(ostream);1437p.writeObject(nf);1438ostream.close();1439*/14401441// File minint maxint minfrac maxfrac1442// NumberFormat4185761a 0x122 0x121 0x124 0x1231443// NumberFormat4185761b 0x311 0x312 0x313 0x3141444// File a is bad because the mins are smaller than the maxes.1445// File b is bad because the values are too big for a DecimalFormat.1446// These files have a sufix ".ser.txt".14471448InputStream istream = HexDumpReader.getStreamFromHexDump("NumberFormat4185761a.ser.txt");1449ObjectInputStream p = new ObjectInputStream(istream);1450try {1451NumberFormat nf = (NumberFormat) p.readObject();1452errln("FAIL: Deserialized bogus NumberFormat int:" +1453nf.getMinimumIntegerDigits() + ".." +1454nf.getMaximumIntegerDigits() + " frac:" +1455nf.getMinimumFractionDigits() + ".." +1456nf.getMaximumFractionDigits());1457} catch (InvalidObjectException e) {1458logln("Ok: " + e.getMessage());1459}1460istream.close();14611462istream = HexDumpReader.getStreamFromHexDump("NumberFormat4185761b.ser.txt");1463p = new ObjectInputStream(istream);1464try {1465NumberFormat nf = (NumberFormat) p.readObject();1466errln("FAIL: Deserialized bogus DecimalFormat int:" +1467nf.getMinimumIntegerDigits() + ".." +1468nf.getMaximumIntegerDigits() + " frac:" +1469nf.getMinimumFractionDigits() + ".." +1470nf.getMaximumFractionDigits());1471} catch (InvalidObjectException e) {1472logln("Ok: " + e.getMessage());1473}1474istream.close();1475}147614771478/**1479* Some DecimalFormatSymbols changes are not picked up by DecimalFormat.1480* This includes the minus sign, currency symbol, international currency1481* symbol, percent, and permille. This is filed as bugs 4212072 and1482* 4212073.1483*/1484public void Test4212072() throws IOException, ClassNotFoundException {1485DecimalFormatSymbols sym = DecimalFormatSymbols.getInstance(Locale.US);1486DecimalFormat fmt = new DecimalFormat("#", sym);14871488sym.setMinusSign('^');1489fmt.setDecimalFormatSymbols(sym);1490if (!fmt.format(-1).equals("^1")) {1491errln("FAIL: -1 x (minus=^) -> " + fmt.format(-1) +1492", exp ^1");1493}1494if (!fmt.getNegativePrefix().equals("^")) {1495errln("FAIL: (minus=^).getNegativePrefix -> " +1496fmt.getNegativePrefix() + ", exp ^");1497}1498sym.setMinusSign('-');14991500fmt.applyPattern("#%");1501sym.setPercent('^');1502fmt.setDecimalFormatSymbols(sym);1503if (!fmt.format(0.25).equals("25^")) {1504errln("FAIL: 0.25 x (percent=^) -> " + fmt.format(0.25) +1505", exp 25^");1506}1507if (!fmt.getPositiveSuffix().equals("^")) {1508errln("FAIL: (percent=^).getPositiveSuffix -> " +1509fmt.getPositiveSuffix() + ", exp ^");1510}1511sym.setPercent('%');15121513fmt.applyPattern("#\u2030");1514sym.setPerMill('^');1515fmt.setDecimalFormatSymbols(sym);1516if (!fmt.format(0.25).equals("250^")) {1517errln("FAIL: 0.25 x (permill=^) -> " + fmt.format(0.25) +1518", exp 250^");1519}1520if (!fmt.getPositiveSuffix().equals("^")) {1521errln("FAIL: (permill=^).getPositiveSuffix -> " +1522fmt.getPositiveSuffix() + ", exp ^");1523}1524sym.setPerMill('\u2030');15251526fmt.applyPattern("\u00A4#.00");1527sym.setCurrencySymbol("usd");1528fmt.setDecimalFormatSymbols(sym);1529if (!fmt.format(12.5).equals("usd12.50")) {1530errln("FAIL: 12.5 x (currency=usd) -> " + fmt.format(12.5) +1531", exp usd12.50");1532}1533if (!fmt.getPositivePrefix().equals("usd")) {1534errln("FAIL: (currency=usd).getPositivePrefix -> " +1535fmt.getPositivePrefix() + ", exp usd");1536}1537sym.setCurrencySymbol("$");15381539fmt.applyPattern("\u00A4\u00A4#.00");1540sym.setInternationalCurrencySymbol("DOL");1541fmt.setDecimalFormatSymbols(sym);1542if (!fmt.format(12.5).equals("DOL12.50")) {1543errln("FAIL: 12.5 x (intlcurrency=DOL) -> " + fmt.format(12.5) +1544", exp DOL12.50");1545}1546if (!fmt.getPositivePrefix().equals("DOL")) {1547errln("FAIL: (intlcurrency=DOL).getPositivePrefix -> " +1548fmt.getPositivePrefix() + ", exp DOL");1549}1550sym.setInternationalCurrencySymbol("USD");15511552// Since the pattern logic has changed, make sure that patterns round1553// trip properly. Test stream in/out integrity too.1554Locale[] avail = NumberFormat.getAvailableLocales();1555for (int i=0; i<avail.length; ++i) {1556for (int j=0; j<3; ++j) {1557NumberFormat nf;1558switch (j) {1559case 0:1560nf = NumberFormat.getInstance(avail[i]);1561break;1562case 1:1563nf = NumberFormat.getCurrencyInstance(avail[i]);1564break;1565default:1566nf = NumberFormat.getPercentInstance(avail[i]);1567break;1568}1569DecimalFormat df = (DecimalFormat) nf;15701571// Test toPattern/applyPattern round trip1572String pat = df.toPattern();1573DecimalFormatSymbols symb = DecimalFormatSymbols.getInstance(avail[i]);1574DecimalFormat f2 = new DecimalFormat(pat, symb);1575if (!df.equals(f2)) {1576errln("FAIL: " + avail[i] + " -> \"" + pat +1577"\" -> \"" + f2.toPattern() + '"');1578}15791580// Test toLocalizedPattern/applyLocalizedPattern round trip1581pat = df.toLocalizedPattern();1582f2.applyLocalizedPattern(pat);1583if (!df.equals(f2)) {1584errln("FAIL: " + avail[i] + " -> localized \"" + pat +1585"\" -> \"" + f2.toPattern() + '"');1586}15871588// Test writeObject/readObject round trip1589ByteArrayOutputStream baos = new ByteArrayOutputStream();1590ObjectOutputStream oos = new ObjectOutputStream(baos);1591oos.writeObject(df);1592oos.flush();1593baos.close();1594byte[] bytes = baos.toByteArray();1595ObjectInputStream ois =1596new ObjectInputStream(new ByteArrayInputStream(bytes));1597f2 = (DecimalFormat) ois.readObject();1598if (!df.equals(f2)) {1599errln("FAIL: Stream in/out " + avail[i] + " -> \"" + pat +1600"\" -> " +1601(f2 != null ? ("\""+f2.toPattern()+'"') : "null"));1602}16031604}1605}1606}16071608/**1609* DecimalFormat.parse() fails for mulipliers 2^n.1610*/1611public void Test4216742() throws ParseException {1612DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance(Locale.US);1613long[] DATA = { Long.MIN_VALUE, Long.MAX_VALUE, -100000000L, 100000000L};1614for (int i=0; i<DATA.length; ++i) {1615String str = Long.toString(DATA[i]);1616for (int m = 1; m <= 100; m++) {1617fmt.setMultiplier(m);1618long n = ((Number) fmt.parse(str)).longValue();1619if (n > 0 != DATA[i] > 0) {1620errln("\"" + str + "\" parse(x " + fmt.getMultiplier() +1621") => " + n);1622}1623}1624}1625}16261627/**1628* DecimalFormat formats 1.001 to "1.00" instead of "1" with 2 fraction1629* digits.1630*/1631public void Test4217661() {1632Object[] DATA = {1633new Double(0.001), "0",1634new Double(1.001), "1",1635new Double(0.006), "0.01",1636new Double(1.006), "1.01",1637};1638NumberFormat fmt = NumberFormat.getInstance(Locale.US);1639fmt.setMaximumFractionDigits(2);1640for (int i=0; i<DATA.length; i+=2) {1641String s = fmt.format(((Double) DATA[i]).doubleValue());1642if (!s.equals(DATA[i+1])) {1643errln("FAIL: Got " + s + ", exp " + DATA[i+1]);1644}1645}1646}16471648/**1649* 4243011: Formatting .5 rounds to "1" instead of "0"1650*/1651public void Test4243011() {1652Locale savedLocale = Locale.getDefault();1653Locale.setDefault(Locale.US);1654double DATA[] = {0.5, 1.5, 2.5, 3.5, 4.5};1655String EXPECTED[] = {"0.", "2.", "2.", "4.", "4."};16561657DecimalFormat format = new DecimalFormat("0.");1658for (int i = 0; i < DATA.length; i++) {1659String result = format.format(DATA[i]);1660if (result.equals(EXPECTED[i])) {1661logln("OK: got " + result);1662} else {1663errln("FAIL: got " + result);1664}1665}1666Locale.setDefault(savedLocale);1667}16681669/**1670* 4243108: format(0.0) gives "0.1" if preceded by parse("99.99")1671*/1672public void Test4243108() {1673Locale savedLocale = Locale.getDefault();1674Locale.setDefault(Locale.US);1675DecimalFormat f = new DecimalFormat("#.#");1676String result = f.format(0.0);1677if (result.equals("0")) {1678logln("OK: got " + result);1679} else {1680errln("FAIL: got " + result);1681}1682try {1683double dResult = f.parse("99.99").doubleValue();1684if (dResult == 99.99) {1685logln("OK: got " + dResult);1686} else {1687errln("FAIL: got " + dResult);1688}1689} catch (ParseException e) {1690errln("Caught a ParseException:");1691e.printStackTrace();1692}1693result = f.format(0.0);1694if (result.equals("0")) {1695logln("OK: got " + result);1696} else {1697errln("FAIL: got " + result);1698}1699Locale.setDefault(savedLocale);1700}17011702/**1703* 4330377: DecimalFormat engineering notation gives incorrect results1704*/1705public void test4330377() {1706Locale savedLocale = Locale.getDefault();1707Locale.setDefault(Locale.US);1708double[] input = {5000.0, 500.0, 50.0, 5.0, 0.5, 0.05, 0.005, 0.0005,17095050.0, 505.0, 50.5, 5.05, 0.505, 0.0505, 0.00505, 0.000505};1710String[] pattern = {"000.#E0", "##0.#E0", "#00.#E0"};1711String[][] expected = {1712// it's questionable whether "#00.#E0" should result in post-decimal1713// zeroes, i.e., whether "5.0E3", "5.0E0", "5.0E-3" are really good1714{"500E1", "5E3", "5.0E3"},1715{"500E0", "500E0", "500E0"},1716{"500E-1", "50E0", "50E0"},1717{"500E-2", "5E0", "5.0E0"},1718{"500E-3", "500E-3", "500E-3"},1719{"500E-4", "50E-3", "50E-3"},1720{"500E-5", "5E-3", "5.0E-3"},1721{"500E-6", "500E-6", "500E-6"},1722{"505E1", "5.05E3", "5.05E3"},1723{"505E0", "505E0", "505E0"},1724{"505E-1", "50.5E0", "50.5E0"},1725{"505E-2", "5.05E0", "5.05E0"},1726{"505E-3", "505E-3", "505E-3"},1727{"505E-4", "50.5E-3", "50.5E-3"},1728{"505E-5", "5.05E-3", "5.05E-3"},1729{"505E-6", "505E-6", "505E-6"}1730};1731for (int i = 0; i < input.length; i++) {1732for (int j = 0; j < pattern.length; j++) {1733DecimalFormat format = new DecimalFormat(pattern[j]);1734String result = format.format(input[i]);1735if (!result.equals(expected[i][j])) {1736errln("FAIL: input: " + input[i] +1737", pattern: " + pattern[j] +1738", expected: " + expected[i][j] +1739", got: " + result);1740}1741}1742}1743Locale.setDefault(savedLocale);1744}17451746/**1747* 4233840: NumberFormat does not round correctly1748*/1749public void test4233840() {1750float f = 0.0099f;17511752NumberFormat nf = new DecimalFormat("0.##", DecimalFormatSymbols.getInstance(Locale.US));1753nf.setMinimumFractionDigits(2);17541755String result = nf.format(f);17561757if (!result.equals("0.01")) {1758errln("FAIL: input: " + f + ", expected: 0.01, got: " + result);1759}1760}17611762/**1763* 4241880: Decimal format doesnt round a double properly when the number is less than 11764*/1765public void test4241880() {1766Locale savedLocale = Locale.getDefault();1767Locale.setDefault(Locale.US);1768double[] input = {1769.019, .009, .015, .016, .014,1770.004, .005, .006, .007, .008,1771.5, 1.5, .25, .55, .045,1772.035, .0005, .0015,1773};1774String[] pattern = {1775"##0%", "##0%", "##0%", "##0%", "##0%",1776"##0%", "##0%", "##0%", "##0%", "##0%",1777"#,##0", "#,##0", "#,##0.0", "#,##0.0", "#,##0.00",1778"#,##0.00", "#,##0.000", "#,##0.000",1779};1780String[] expected = {1781"2%", "1%", "2%", "2%", "1%",1782"0%", "0%", "1%", "1%", "1%",1783"0", "2", "0.2", "0.6", "0.04",1784"0.04", "0.000", "0.002",1785};1786for (int i = 0; i < input.length; i++) {1787DecimalFormat format = new DecimalFormat(pattern[i]);1788String result = format.format(input[i]);1789if (!result.equals(expected[i])) {1790errln("FAIL: input: " + input[i] +1791", pattern: " + pattern[i] +1792", expected: " + expected[i] +1793", got: " + result);1794}1795}1796Locale.setDefault(savedLocale);1797}1798}17991800class myformat implements Serializable1801{1802DateFormat _dateFormat = DateFormat.getDateInstance();18031804public String Now()1805{1806GregorianCalendar calendar = new GregorianCalendar();1807Date t = calendar.getTime();1808String nowStr = _dateFormat.format(t);1809return nowStr;1810}1811}18121813class MyNumberFormatTest extends NumberFormat {1814public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {1815return new StringBuffer("");1816}1817public StringBuffer format(long number,StringBuffer toAppendTo, FieldPosition pos) {1818return new StringBuffer("");1819}1820public Number parse(String text, ParsePosition parsePosition) {1821return new Integer(0);1822}1823}182418251826