-//##header\r
-/*****************************************************************************************\r
- *\r
- * Copyright (C) 1996-2009, International Business Machines\r
- * Corporation and others. All Rights Reserved.\r
- **/\r
-\r
-/** \r
- * Port From: JDK 1.4b1 : java.text.Format.NumberRegression\r
- * Source File: java/text/format/NumberRegression.java\r
- **/\r
- \r
-/**\r
- * @test 1.49 01/05/21\r
- * @bug 4052223 4059870 4061302 4062486 4066646 4068693 4070798 4071005 4071014\r
- * 4071492 4071859 4074454 4074620 4075713 4083018 4086575 4087244 4087245\r
- * 4087251 4087535 4088161 4088503 4090489 4090504 4092480 4092561 4095713\r
- * 4098741 4099404 4101481 4106658 4106662 4106664 4108738 4110936 4122840\r
- * 4125885 4134034 4134300 4140009 4141750 4145457 4147295 4147706 4162198\r
- * 4162852 4167494 4170798 4176114 4179818 4185761 4212072 4212073 4216742\r
- * 4217661 4243011 4243108 4330377 4233840\r
- * @summary Regression tests for NumberFormat and associated classes\r
- */\r
-\r
-package com.ibm.icu.dev.test.format;\r
-\r
-//import com.ibm.icu.impl.ICULocaleData;\r
-import com.ibm.icu.impl.ICUResourceBundle;\r
-import com.ibm.icu.text.*;\r
-import com.ibm.icu.util.*;\r
-\r
-import java.io.*;\r
-import java.math.BigInteger;\r
-import java.text.FieldPosition;\r
-import java.text.ParseException;\r
-import java.text.ParsePosition;\r
-import java.util.Date;\r
-import java.util.Locale;\r
-\r
-public class NumberRegression extends com.ibm.icu.dev.test.TestFmwk {\r
-\r
- public static void main(String[] args) throws Exception {\r
- new NumberRegression().run(args);\r
- }\r
-\r
- private static final char EURO = '\u20ac';\r
-\r
- /**\r
- * NumberFormat.equals comparing with null should always return false.\r
- */\r
- public void Test4075713(){\r
-\r
- try {\r
- MyNumberFormatTest tmp = new MyNumberFormatTest();\r
- if (!tmp.equals(null))\r
- logln("NumberFormat.equals passed");\r
- } catch (NullPointerException e) {\r
- errln("(new MyNumberFormatTest()).equals(null) throws unexpected exception");\r
- }\r
- }\r
-\r
- /**\r
- * NumberFormat.equals comparing two obj equal even the setGroupingUsed\r
- * flag is different.\r
- */\r
- public void Test4074620() {\r
-\r
- MyNumberFormatTest nf1 = new MyNumberFormatTest();\r
- MyNumberFormatTest nf2 = new MyNumberFormatTest();\r
-\r
- nf1.setGroupingUsed(false);\r
- nf2.setGroupingUsed(true);\r
-\r
- if (nf1.equals(nf2)) errln("Test for bug 4074620 failed");\r
- else logln("Test for bug 4074620 passed.");\r
- return;\r
- }\r
-\r
-\r
- /**\r
- * DecimalFormat.format() incorrectly uses maxFractionDigits setting.\r
- */\r
-\r
- public void Test4088161 (){\r
- DecimalFormat df = new DecimalFormat();\r
- double d = 100;\r
- df.setMinimumFractionDigits(0);\r
- df.setMaximumFractionDigits(16);\r
- StringBuffer sBuf1 = new StringBuffer("");\r
- FieldPosition fp1 = new FieldPosition(0);\r
- logln("d = " + d);\r
- logln("maxFractionDigits = " + df.getMaximumFractionDigits());\r
- logln(" format(d) = '" + df.format(d, sBuf1, fp1) + "'");\r
- df.setMaximumFractionDigits(17);\r
- StringBuffer sBuf2 = new StringBuffer("");\r
- FieldPosition fp2 = new FieldPosition(0);\r
- logln("maxFractionDigits = " + df.getMaximumFractionDigits());\r
- df.format(d, sBuf2, fp2);\r
- if (!sBuf2.toString().equals("100"))\r
- errln(" format(d) = '" + sBuf2 + "'");\r
- }\r
- /**\r
- * DecimalFormatSymbols should be cloned in the ctor DecimalFormat.\r
- * DecimalFormat(String, DecimalFormatSymbols).\r
- */\r
- public void Test4087245 (){\r
- DecimalFormatSymbols symbols = new DecimalFormatSymbols();\r
- DecimalFormat df = new DecimalFormat("#,##0.0", symbols);\r
- long n = 123;\r
- StringBuffer buf1 = new StringBuffer();\r
- StringBuffer buf2 = new StringBuffer();\r
- logln("format(" + n + ") = " +\r
- df.format(n, buf1, new FieldPosition(0)));\r
- symbols.setDecimalSeparator('p'); // change value of field\r
- logln("format(" + n + ") = " +\r
- df.format(n, buf2, new FieldPosition(0)));\r
- if (!buf1.toString().equals(buf2.toString()))\r
- errln("Test for bug 4087245 failed");\r
- }\r
- /**\r
- * DecimalFormat.format() incorrectly formats 0.0\r
- */\r
- public void Test4087535 ()\r
- {\r
- DecimalFormat df = new DecimalFormat();\r
- df.setMinimumIntegerDigits(0);\r
-\r
- double n = 0;\r
- String buffer = new String();\r
- buffer = df.format(n);\r
- if (buffer.length() == 0)\r
- errln(n + ": '" + buffer + "'");\r
- n = 0.1;\r
- buffer = df.format(n);\r
- if (buffer.length() == 0)\r
- errln(n + ": '" + buffer + "'");\r
- }\r
-\r
- /**\r
- * DecimalFormat.format fails when groupingSize is set to 0.\r
- */\r
- public void Test4088503 (){\r
- DecimalFormat df = new DecimalFormat();\r
- df.setGroupingSize(0);\r
- StringBuffer sBuf = new StringBuffer("");\r
- FieldPosition fp = new FieldPosition(0);\r
- try {\r
- logln(df.format(123, sBuf, fp).toString());\r
- } catch (Exception foo) {\r
- errln("Test for bug 4088503 failed.");\r
- }\r
-\r
- }\r
- /**\r
- * NumberFormat.getCurrencyInstance is wrong.\r
- */\r
- public void Test4066646 () {\r
- //float returnfloat = 0.0f; //The variable is never used\r
- assignFloatValue(2.04f);\r
- assignFloatValue(2.03f);\r
- assignFloatValue(2.02f);\r
- assignFloatValue(0.0f);\r
- }\r
-\r
- public float assignFloatValue(float returnfloat)\r
- {\r
- logln(" VALUE " + returnfloat);\r
- NumberFormat nfcommon = NumberFormat.getCurrencyInstance(Locale.US);\r
- nfcommon.setGroupingUsed(false);\r
-\r
- String stringValue = nfcommon.format(returnfloat).substring(1);\r
- if (Float.valueOf(stringValue).floatValue() != returnfloat)\r
- errln(" DISPLAYVALUE " + stringValue);\r
- return returnfloat;\r
- } // End Of assignFloatValue()\r
-\r
- /**\r
- * DecimalFormat throws exception when parsing "0"\r
- */\r
- public void Test4059870() {\r
- DecimalFormat format = new DecimalFormat("00");\r
- try {\r
- logln(format.parse("0").toString());\r
- } catch (Exception e) { errln("Test for bug 4059870 failed : " + e); }\r
- }\r
- /**\r
- * DecimalFormatSymbol.equals should always return false when\r
- * comparing with null.\r
- */\r
-\r
- public void Test4083018 (){\r
- DecimalFormatSymbols dfs = new DecimalFormatSymbols();\r
- try {\r
- if (!dfs.equals(null))\r
- logln("Test Passed!");\r
- } catch (Exception foo) {\r
- errln("Test for bug 4083018 failed => Message : " + foo.getMessage());\r
- }\r
- }\r
- /**\r
- * DecimalFormat does not round up correctly.\r
- */\r
- public void Test4071492 (){\r
- double x = 0.00159999;\r
- NumberFormat nf = NumberFormat.getInstance();\r
- nf.setMaximumFractionDigits(4);\r
- String out = nf.format(x);\r
- logln("0.00159999 formats with 4 fractional digits to " + out);\r
- String expected = "0.0016";\r
- if (!out.equals(expected))\r
- errln("FAIL: Expected " + expected);\r
- }\r
-\r
- /**\r
- * A space as a group separator for localized pattern causes\r
- * wrong format. WorkAround : use non-breaking space.\r
- */\r
- public void Test4086575() {\r
-\r
- NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE);\r
- logln("nf toPattern1: " + ((DecimalFormat)nf).toPattern());\r
- logln("nf toLocPattern1: " + ((DecimalFormat)nf).toLocalizedPattern());\r
-\r
- // No group separator\r
- logln("...applyLocalizedPattern ###,00;(###,00) ");\r
- ((DecimalFormat)nf).applyLocalizedPattern("###,00;(###,00)");\r
- logln("nf toPattern2: " + ((DecimalFormat)nf).toPattern());\r
- logln("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern());\r
-\r
- logln("nf: " + nf.format(1234)); // 1234,00\r
- logln("nf: " + nf.format(-1234)); // (1234,00)\r
-\r
- // Space as group separator\r
-\r
- logln("...applyLocalizedPattern # ###,00;(# ###,00) ");\r
- ((DecimalFormat)nf).applyLocalizedPattern("#\u00a0###,00;(#\u00a0###,00)");\r
- logln("nf toPattern2: " + ((DecimalFormat)nf).toPattern());\r
- logln("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern());\r
- String buffer = nf.format(1234);\r
- if (!buffer.equals("1\u00a0234,00"))\r
- errln("nf : " + buffer); // Expect 1 234,00\r
- buffer = nf.format(-1234);\r
- if (!buffer.equals("(1\u00a0234,00)"))\r
- errln("nf : " + buffer); // Expect (1 234,00)\r
-\r
- // Erroneously prints:\r
- // 1234,00 ,\r
- // (1234,00 ,)\r
-\r
- }\r
- /**\r
- * DecimalFormat.parse returns wrong value\r
- */\r
- public void Test4068693()\r
- {\r
- logln("----- Test Application -----");\r
- //ParsePosition pos;\r
- DecimalFormat df = new DecimalFormat();\r
- Number d = df.parse("123.55456", new ParsePosition(0));\r
- if (!d.toString().equals("123.55456")) {\r
- errln("Result -> " + d.doubleValue());\r
- }\r
- }\r
-\r
- /* bugs 4069754, 4067878\r
- * null pointer thrown when accessing a deserialized DecimalFormat\r
- * object.\r
- */\r
- public void Test4069754() throws Exception\r
- {\r
- //try {\r
- ByteArrayOutputStream baos = new ByteArrayOutputStream();\r
- ObjectOutputStream oos = new ObjectOutputStream(baos);\r
- myformat it = new myformat();\r
- logln(it.Now());\r
- oos.writeObject(it);\r
- oos.flush();\r
- baos.close();\r
- logln("Save OK!");\r
- byte [] bytes = baos.toByteArray();\r
- ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));\r
- myformat o = (myformat)ois.readObject();\r
- ois.close();\r
- it.Now();\r
- logln("Load OK!");\r
- if (!o._dateFormat.equals(it._dateFormat)) {\r
- throw new Exception("The saved and loaded object are not equals!");\r
- }\r
- logln("Compare OK!");\r
- //} catch (Exception foo) {\r
- //errln("Test for bug 4069754 or 4057878 failed => Exception: " + foo.getMessage());\r
- //}\r
- }\r
-\r
- /**\r
- * DecimalFormat.applyPattern(String) allows illegal patterns\r
- */\r
- public void Test4087251 (){\r
- DecimalFormat df = new DecimalFormat();\r
- try {\r
- df.applyPattern("#.#.#");\r
- logln("toPattern() returns \"" + df.toPattern() + "\"");\r
- errln("applyPattern(\"#.#.#\") doesn't throw IllegalArgumentException");\r
- } catch (IllegalArgumentException e) {\r
- logln("Caught Illegal Argument Error !");\r
- }\r
- // Second test; added 5/11/98 when reported to fail on 1.2b3\r
- try {\r
- df.applyPattern("#0.0#0#0");\r
- logln("toPattern() returns \"" + df.toPattern() + "\"");\r
- errln("applyPattern(\"#0.0#0#0\") doesn't throw IllegalArgumentException");\r
- } catch (IllegalArgumentException e) {\r
- logln("Ok - IllegalArgumentException for #0.0#0#0");\r
- }\r
- }\r
-\r
- /**\r
- * DecimalFormat.format() loses precision\r
- */\r
- public void Test4090489 (){\r
- DecimalFormat df = new DecimalFormat();\r
- df.setMinimumFractionDigits(10);\r
- df.setGroupingUsed(false);\r
- double d = 1.000000000000001E7;\r
- java.math.BigDecimal bd = new java.math.BigDecimal(d);\r
- StringBuffer sb = new StringBuffer("");\r
- FieldPosition fp = new FieldPosition(0);\r
- logln("d = " + d);\r
- logln("BigDecimal.toString(): " + bd.toString());\r
- df.format(d, sb, fp);\r
- if (!sb.toString().equals("10000000.0000000100")) {\r
- errln("DecimalFormat.format(): " + sb.toString());\r
- }\r
- }\r
-\r
- /**\r
- * DecimalFormat.format() loses precision\r
- */\r
- public void Test4090504 ()\r
- {\r
- double d = 1;\r
- logln("d = " + d);\r
- DecimalFormat df = new DecimalFormat();\r
- StringBuffer sb;\r
- FieldPosition fp;\r
- try {\r
- for (int i = 17; i <= 20; i++) {\r
- df.setMaximumFractionDigits(i);\r
- sb = new StringBuffer("");\r
- fp = new FieldPosition(0);\r
- logln(" getMaximumFractionDigits() = " + i);\r
- logln(" formated: " + df.format(d, sb, fp));\r
- }\r
- } catch (Exception foo) {\r
- errln("Bug 4090504 regression test failed. Message : " + foo.getMessage());\r
- }\r
- }\r
- /**\r
- * DecimalFormat.parse(String str, ParsePosition pp) loses precision\r
- */\r
- public void Test4095713 ()\r
- {\r
- DecimalFormat df = new DecimalFormat();\r
- String str = "0.1234";\r
- Double d1 = new Double(str);\r
- Number d2 = df.parse(str, new ParsePosition(0));\r
- logln(d1.toString());\r
- if (d2.doubleValue() != d1.doubleValue())\r
- errln("Bug 4095713 test failed, new double value : " + d2.doubleValue());\r
- }\r
-\r
- /**\r
- * DecimalFormat.parse() fails when multiplier is not set to 1\r
- */\r
- public void Test4092561 ()\r
- {\r
- Locale savedLocale = Locale.getDefault();\r
- Locale.setDefault(Locale.US);\r
- DecimalFormat df = new DecimalFormat();\r
- String str = Long.toString(Long.MIN_VALUE);\r
- logln("Long.MIN_VALUE : " + df.parse(str, new ParsePosition(0)).toString());\r
- df.setMultiplier(100);\r
- Number num = df.parse(str, new ParsePosition(0));\r
- if (num.doubleValue() != -9.223372036854776E16) {\r
- errln("Bug 4092561 test failed when multiplier is set to not 1.");\r
- }\r
- Locale.setDefault(savedLocale);\r
- }\r
-\r
- /**\r
- * DecimalFormat: Negative format ignored.\r
- */\r
- public void Test4092480 ()\r
- {\r
- DecimalFormat dfFoo = new DecimalFormat("000");\r
-\r
- try {\r
- dfFoo.applyPattern("0000;-000");\r
- if (!dfFoo.toPattern().equals("#0000"))\r
- errln("dfFoo.toPattern : " + dfFoo.toPattern());\r
- logln(dfFoo.format(42));\r
- logln(dfFoo.format(-42));\r
- dfFoo.applyPattern("000;-000");\r
- if (!dfFoo.toPattern().equals("#000"))\r
- errln("dfFoo.toPattern : " + dfFoo.toPattern());\r
- logln(dfFoo.format(42));\r
- logln(dfFoo.format(-42));\r
-\r
- dfFoo.applyPattern("000;-0000");\r
- if (!dfFoo.toPattern().equals("#000"))\r
- errln("dfFoo.toPattern : " + dfFoo.toPattern());\r
- logln(dfFoo.format(42));\r
- logln(dfFoo.format(-42));\r
-\r
- dfFoo.applyPattern("0000;-000");\r
- if (!dfFoo.toPattern().equals("#0000"))\r
- errln("dfFoo.toPattern : " + dfFoo.toPattern());\r
- logln(dfFoo.format(42));\r
- logln(dfFoo.format(-42));\r
- } catch (Exception foo) {\r
- errln("Message " + foo.getMessage());\r
- }\r
- }\r
- /**\r
- * NumberFormat.getCurrencyInstance() produces format that uses\r
- * decimal separator instead of monetary decimal separator.\r
- *\r
- * Rewrote this test not to depend on the actual pattern. Pattern should\r
- * never contain the monetary separator! Decimal separator in pattern is\r
- * interpreted as monetary separator if currency symbol is seen!\r
- */\r
- public void Test4087244 () {\r
- Locale de = new Locale("pt", "PT");\r
- DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(de);\r
- DecimalFormatSymbols sym = df.getDecimalFormatSymbols();\r
- sym.setMonetaryDecimalSeparator('$');\r
- df.setDecimalFormatSymbols(sym);\r
- char decSep = sym.getDecimalSeparator();\r
- char monSep = sym.getMonetaryDecimalSeparator();\r
- //char zero = sym.getZeroDigit(); //The variable is never used\r
- if (decSep == monSep) {\r
- errln("ERROR in test: want decimal sep != monetary sep");\r
- } else {\r
- df.setMinimumIntegerDigits(1);\r
- df.setMinimumFractionDigits(2);\r
- String str = df.format(1.23);\r
- String monStr = "1" + monSep + "23";\r
- String decStr = "1" + decSep + "23";\r
- if (str.indexOf(monStr) >= 0 && str.indexOf(decStr) < 0) {\r
- logln("OK: 1.23 -> \"" + str + "\" contains \"" +\r
- monStr + "\" and not \"" + decStr + '"');\r
- } else {\r
- errln("FAIL: 1.23 -> \"" + str + "\", should contain \"" +\r
- monStr +\r
- "\" and not \"" + decStr + '"');\r
- }\r
- }\r
- }\r
- /**\r
- * Number format data rounding errors for locale FR\r
- */\r
- public void Test4070798 () {\r
- NumberFormat formatter;\r
- String tempString;\r
- /* User error :\r
- String expectedDefault = "-5\u00a0789,987";\r
- String expectedCurrency = "5\u00a0789,98\u00a0F";\r
- String expectedPercent = "-578\u00a0998%";\r
- */\r
- String expectedDefault = "-5\u00a0789,988";\r
- String expectedCurrency = "5\u00a0789,99\u00a0" + EURO; // euro\r
- String expectedPercent = "-578\u00a0999\u00a0%";\r
-\r
- formatter = NumberFormat.getNumberInstance(Locale.FRANCE);\r
- tempString = formatter.format (-5789.9876);\r
-\r
- if (tempString.equals(expectedDefault)) {\r
- logln ("Bug 4070798 default test passed.");\r
- } else {\r
- errln("Failed:" +\r
- " Expected " + expectedDefault +\r
- " Received " + tempString );\r
- }\r
-\r
-\r
- formatter = NumberFormat.getCurrencyInstance(Locale.FRANCE);\r
- tempString = formatter.format( 5789.9876 );\r
-\r
- if (tempString.equals(expectedCurrency) ) {\r
- logln ("Bug 4070798 currency test assed.");\r
- } else {\r
- errln("Failed:" +\r
- " Expected " + expectedCurrency +\r
- " Received " + tempString );\r
- }\r
-\r
-\r
- formatter = NumberFormat.getPercentInstance(Locale.FRANCE);\r
- tempString = formatter.format (-5789.9876);\r
-\r
- if (tempString.equals(expectedPercent) ) {\r
- logln ("Bug 4070798 percentage test passed.");\r
- } else {\r
- errln("Failed:" +\r
- " Expected " + expectedPercent +\r
- " Received " + tempString );\r
- }\r
- }\r
- /**\r
- * Data rounding errors for French (Canada) locale\r
- */\r
- public void Test4071005 () {\r
-\r
- NumberFormat formatter;\r
- String tempString;\r
- /* user error :\r
- String expectedDefault = "-5 789,987";\r
- String expectedCurrency = "5 789,98\u00a0$";\r
- String expectedPercent = "-578 998%";\r
- */\r
- String expectedDefault = "-5\u00a0789,988";\r
- String expectedCurrency = "5\u00a0789,99\u00a0$";\r
- String expectedPercent = "-578\u00a0999\u00A0%";\r
-\r
- formatter = NumberFormat.getNumberInstance(Locale.CANADA_FRENCH);\r
- tempString = formatter.format (-5789.9876);\r
- if (tempString.equals(expectedDefault)) {\r
- logln ("Bug 4071005 default test passed.");\r
- } else {\r
- errln("Failed:" +\r
- " Expected " + expectedDefault +\r
- " Received " + tempString );\r
- }\r
-\r
- formatter = NumberFormat.getCurrencyInstance(Locale.CANADA_FRENCH);\r
- tempString = formatter.format( 5789.9876 ) ;\r
-\r
- if (tempString.equals(expectedCurrency) ) {\r
- logln ("Bug 4071005 currency test passed.");\r
- } else {\r
- errln("Failed:" +\r
- " Expected " + expectedCurrency +\r
- " Received " + tempString );\r
- }\r
- formatter = NumberFormat.getPercentInstance(Locale.CANADA_FRENCH);\r
- tempString = formatter.format (-5789.9876);\r
-\r
- if (tempString.equals(expectedPercent) ) {\r
- logln ("Bug 4071005 percentage test passed.");\r
- } else {\r
- errln("Failed:" +\r
- " Expected " + expectedPercent +\r
- " Received " + tempString );\r
- }\r
- }\r
-\r
- /**\r
- * Data rounding errors for German (Germany) locale\r
- */\r
- public void Test4071014 () {\r
- NumberFormat formatter;\r
- String tempString;\r
- /* user error :\r
- String expectedDefault = "-5.789,987";\r
- String expectedCurrency = "5.789,98\u00a0DM";\r
- String expectedPercent = "-578.998%";\r
- */\r
- String expectedDefault = "-5.789,988";\r
- String expectedCurrency = "5.789,99\u00a0" + EURO;\r
- String expectedPercent = "-578.999\u00a0%";\r
-\r
- formatter = NumberFormat.getNumberInstance(Locale.GERMANY);\r
- tempString = formatter.format (-5789.9876);\r
-\r
- if (tempString.equals(expectedDefault)) {\r
- logln ("Bug 4071014 default test passed.");\r
- } else {\r
- errln("Failed:" +\r
- " Expected " + expectedDefault +\r
- " Received " + tempString );\r
- }\r
-\r
- formatter = NumberFormat.getCurrencyInstance(Locale.GERMANY);\r
- tempString = formatter.format( 5789.9876 ) ;\r
-\r
- if (tempString.equals(expectedCurrency) ) {\r
- logln ("Bug 4071014 currency test passed.");\r
- } else {\r
- errln("Failed:" +\r
- " Expected " + expectedCurrency +\r
- " Received " + tempString );\r
- }\r
-\r
- formatter = NumberFormat.getPercentInstance(Locale.GERMANY);\r
- tempString = formatter.format (-5789.9876);\r
-\r
- if (tempString.equals(expectedPercent) ) {\r
- logln ("Bug 4071014 percentage test passed.");\r
- } else {\r
- errln("Failed:" +\r
- " Expected " + expectedPercent +\r
- " Received " + tempString );\r
- }\r
-\r
- }\r
- /**\r
- * Data rounding errors for Italian locale number formats\r
- * Note- with the Euro, there is no need for currency rounding anymore\r
- */\r
- public void Test4071859 () {\r
- NumberFormat formatter;\r
- String tempString;\r
- /* user error :\r
- String expectedDefault = "-5.789,987";\r
- String expectedCurrency = "-L.\u00a05.789,98";\r
- String expectedPercent = "-578.998%";\r
- */\r
- String expectedDefault = "-5.789,988";\r
- String expectedCurrency = "-" + EURO + "\u00a05.789,99";\r
- String expectedPercent = "-578.999%";\r
-\r
- formatter = NumberFormat.getNumberInstance(Locale.ITALY);\r
- tempString = formatter.format (-5789.9876);\r
-\r
- if (tempString.equals(expectedDefault)) {\r
- logln ("Bug 4071859 default test passed.");\r
- } else {\r
- errln("a) Failed:" +\r
- " Expected " + expectedDefault +\r
- " Received " + tempString );\r
- }\r
-\r
- formatter = NumberFormat.getCurrencyInstance(Locale.ITALY);\r
- tempString = formatter.format( -5789.9876 ) ;\r
-\r
- if (tempString.equals(expectedCurrency) ) {\r
- logln ("Bug 4071859 currency test passed.");\r
- } else {\r
- errln("b) Failed:" +\r
- " Expected " + expectedCurrency +\r
- " Received " + tempString );\r
- }\r
-\r
- formatter = NumberFormat.getPercentInstance(Locale.ITALY);\r
- tempString = formatter.format (-5789.9876);\r
-\r
- if (tempString.equals(expectedPercent) ) {\r
- logln ("Bug 4071859 percentage test passed.");\r
- } else {\r
- errln("c) Failed:" +\r
- " Expected " + expectedPercent +\r
- " Received " + tempString );\r
- }\r
-\r
- }\r
- /* bug 4071859\r
- * Test rounding for nearest even.\r
- */\r
- public void Test4093610()\r
- {\r
- DecimalFormat df = new DecimalFormat("#0.#");\r
- roundingTest(df, 12.35, "12.4");\r
- roundingTest(df, 12.45, "12.4");\r
- roundingTest(df, 12.452,"12.5");\r
- roundingTest(df, 12.55, "12.6");\r
- roundingTest(df, 12.65, "12.6");\r
- roundingTest(df, 12.652,"12.7");\r
- roundingTest(df, 12.75, "12.8");\r
- roundingTest(df, 12.752,"12.8");\r
- roundingTest(df, 12.85, "12.8");\r
- roundingTest(df, 12.852,"12.9");\r
- roundingTest(df, 12.95, "13");\r
- roundingTest(df, 12.952,"13");\r
-\r
- }\r
- void roundingTest(DecimalFormat df, double x, String expected)\r
- {\r
- String out = df.format(x);\r
- logln("" + x + " formats with 1 fractional digits to " + out);\r
- if (!out.equals(expected)) errln("FAIL: Expected " + expected);\r
- }\r
- /**\r
- * Tests the setMaximumFractionDigits limit.\r
- */\r
- public void Test4098741()\r
- {\r
- try {\r
- NumberFormat fmt = NumberFormat.getPercentInstance();\r
- fmt.setMaximumFractionDigits(20);\r
- logln(fmt.format(.001));\r
- } catch (Exception foo) {\r
- warnln("Bug 4098471 failed with exception thrown : " + foo.getMessage());\r
- }\r
- }\r
- /**\r
- * Tests illegal pattern exception.\r
- * Fix comment : HShih A31 Part1 will not be fixed and javadoc needs to be updated.\r
- * Part2 has been fixed.\r
- */\r
- public void Test4074454()\r
- {\r
- try {\r
- DecimalFormat fmt = new DecimalFormat("#,#00.00;-#.#");\r
- logln("format 3456.78: " + fmt.format(3456.78)); //fix "The variable 'fmt' is never used"\r
- logln("Inconsistent negative pattern is fine.");\r
- DecimalFormat newFmt = new DecimalFormat("#,#00.00 p''ieces;-#,#00.00 p''ieces");\r
- String tempString = newFmt.format(3456.78);\r
- if (!tempString.equals("3,456.78 p'ieces"))\r
- errln("Failed! 3456.78 p'ieces expected, but got : " + tempString);\r
- } catch (Exception foo) {\r
- warnln("An exception was thrown for any inconsistent negative pattern.");\r
- }\r
- }\r
- /**\r
- * Tests all different comments.\r
- * Response to some comments :\r
- * [1] DecimalFormat.parse API documentation is more than just one line.\r
- * This is not a reproducable doc error in 116 source code.\r
- * [2] See updated javadoc.\r
- * [3] Fixed.\r
- * [4] NumberFormat.parse(String, ParsePosition) : If parsing fails,\r
- * a null object will be returned. The unchanged parse position also\r
- * reflects an error.\r
- * NumberFormat.parse(String) : If parsing fails, an ParseException\r
- * will be thrown.\r
- * See updated javadoc for more details.\r
- * [5] See updated javadoc.\r
- * [6] See updated javadoc.\r
- * [7] This is a correct behavior if the DateFormat object is linient.\r
- * Otherwise, an IllegalArgumentException will be thrown when formatting\r
- * "January 35". See GregorianCalendar class javadoc for more details.\r
- */\r
- public void Test4099404()\r
- {\r
- try {\r
- DecimalFormat fmt = new DecimalFormat("000.0#0");\r
- logln("format 3456.78: " + fmt.format(3456.78)); //fix "The variable 'fmt' is never used"\r
- errln("Bug 4099404 failed applying illegal pattern \"000.0#0\"");\r
- } catch (Exception foo) {\r
- logln("Bug 4099404 pattern \"000.0#0\" passed");\r
- }\r
- try {\r
- DecimalFormat fmt = new DecimalFormat("0#0.000");\r
- logln("format 3456.78: " + fmt.format(3456.78)); //fix "The variable 'fmt' is never used"\r
- errln("Bug 4099404 failed applying illegal pattern \"0#0.000\"");\r
- } catch (Exception foo) {\r
- logln("Bug 4099404 pattern \"0#0.000\" passed");\r
- }\r
- }\r
- /**\r
- * DecimalFormat.applyPattern doesn't set minimum integer digits\r
- */\r
- public void Test4101481()\r
- {\r
- DecimalFormat sdf = new DecimalFormat("#,##0");\r
- if (sdf.getMinimumIntegerDigits() != 1)\r
- errln("Minimum integer digits : " + sdf.getMinimumIntegerDigits());\r
- }\r
- /**\r
- * Tests ParsePosition.setErrorPosition() and ParsePosition.getErrorPosition().\r
- */\r
- public void Test4052223()\r
- {\r
- try {\r
- DecimalFormat fmt = new DecimalFormat("#,#00.00");\r
- Number num = fmt.parse("abc3");\r
- errln("Bug 4052223 failed : can't parse string \"a\". Got " + num);\r
- } catch (ParseException foo) {\r
- logln("Caught expected ParseException : " + foo.getMessage() + " at index : " + foo.getErrorOffset());\r
- }\r
- }\r
- /**\r
- * API tests for API addition request A9.\r
- */\r
- public void Test4061302()\r
- {\r
- DecimalFormatSymbols fmt = new DecimalFormatSymbols();\r
- String currency = fmt.getCurrencySymbol();\r
- String intlCurrency = fmt.getInternationalCurrencySymbol();\r
- char monDecSeparator = fmt.getMonetaryDecimalSeparator();\r
- if (currency.equals("") ||\r
- intlCurrency.equals("") ||\r
- monDecSeparator == 0) {\r
- errln("getCurrencySymbols failed, got empty string.");\r
- }\r
- logln("Before set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator);\r
- fmt.setCurrencySymbol("XYZ");\r
- fmt.setInternationalCurrencySymbol("ABC");\r
- fmt.setMonetaryDecimalSeparator('*');\r
- currency = fmt.getCurrencySymbol();\r
- intlCurrency = fmt.getInternationalCurrencySymbol();\r
- monDecSeparator = fmt.getMonetaryDecimalSeparator();\r
- if (!currency.equals("XYZ") ||\r
- !intlCurrency.equals("ABC") ||\r
- monDecSeparator != '*') {\r
- errln("setCurrencySymbols failed.");\r
- }\r
- logln("After set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator);\r
- }\r
- /**\r
- * API tests for API addition request A23. FieldPosition.getBeginIndex and\r
- * FieldPosition.getEndIndex.\r
- */\r
- public void Test4062486()\r
- {\r
- DecimalFormat fmt = new DecimalFormat("#,##0.00");\r
- StringBuffer formatted = new StringBuffer();\r
- FieldPosition field = new FieldPosition(0);\r
- Double num = new Double(1234.5);\r
- fmt.format(num, formatted, field);\r
- if (field.getBeginIndex() != 0 && field.getEndIndex() != 5)\r
- errln("Format 1234.5 failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex());\r
- field.setBeginIndex(7);\r
- field.setEndIndex(4);\r
- if (field.getBeginIndex() != 7 && field.getEndIndex() != 4)\r
- errln("Set begin/end field indexes failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex());\r
- }\r
-\r
- /**\r
- * DecimalFormat.parse incorrectly works with a group separator.\r
- */\r
- public void Test4108738()\r
- {\r
-\r
- DecimalFormat df = new DecimalFormat("#,##0.###", new\r
- DecimalFormatSymbols(java.util.Locale.US));\r
- String text = "1.222,111";\r
- Number num = df.parse(text,new ParsePosition(0));\r
- if (!num.toString().equals("1.222"))\r
- errln("\"" + text + "\" is parsed as " + num);\r
- text = "1.222x111";\r
- num = df.parse(text,new ParsePosition(0));\r
- if (!num.toString().equals("1.222"))\r
- errln("\"" + text + "\" is parsed as " + num);\r
- }\r
-\r
- /**\r
- * DecimalFormat.format() incorrectly formats negative doubles.\r
- */\r
- public void Test4106658()\r
- {\r
- Locale savedLocale = Locale.getDefault();\r
- Locale.setDefault(Locale.US);\r
- DecimalFormat df = new DecimalFormat(); // Corrected; see 4147706\r
- double d1 = -0.0;\r
- double d2 = -0.0001;\r
- StringBuffer buffer = new StringBuffer();\r
- logln("pattern: \"" + df.toPattern() + "\"");\r
- df.format(d1, buffer, new FieldPosition(0));\r
- if (!buffer.toString().equals("-0")) { // Corrected; see 4147706\r
- errln(d1 + " is formatted as " + buffer);\r
- }\r
- buffer.setLength(0);\r
- df.format(d2, buffer, new FieldPosition(0));\r
- if (!buffer.toString().equals("-0")) { // Corrected; see 4147706\r
- errln(d2 + " is formatted as " + buffer);\r
- }\r
- Locale.setDefault(savedLocale);\r
- }\r
-\r
- /**\r
- * DecimalFormat.parse returns 0 if string parameter is incorrect.\r
- */\r
- public void Test4106662()\r
- {\r
- DecimalFormat df = new DecimalFormat();\r
- String text = "x";\r
- ParsePosition pos1 = new ParsePosition(0), pos2 = new ParsePosition(0);\r
-\r
- logln("pattern: \"" + df.toPattern() + "\"");\r
- Number num = df.parse(text, pos1);\r
- if (num != null) {\r
- errln("Test Failed: \"" + text + "\" is parsed as " + num);\r
- }\r
- df = null;\r
- df = new DecimalFormat("$###.00");\r
- num = df.parse("$", pos2);\r
- if (num != null){\r
- errln("Test Failed: \"$\" is parsed as " + num);\r
- }\r
- }\r
-\r
- /**\r
- * NumberFormat.parse doesn't return null\r
- */\r
- public void Test4114639()\r
- {\r
- NumberFormat format = NumberFormat.getInstance();\r
- String text = "time 10:x";\r
- ParsePosition pos = new ParsePosition(8);\r
- Number result = format.parse(text, pos);\r
- if (result != null) errln("Should return null but got : " + result); // Should be null; it isn't\r
- }\r
-\r
- /**\r
- * DecimalFormat.format(long n) fails if n * multiplier > MAX_LONG.\r
- */\r
- public void Test4106664()\r
- {\r
- DecimalFormat df = new DecimalFormat();\r
- long n = 1234567890123456L;\r
- int m = 12345678;\r
- BigInteger bigN = BigInteger.valueOf(n);\r
- bigN = bigN.multiply(BigInteger.valueOf(m));\r
- df.setMultiplier(m);\r
- df.setGroupingUsed(false);\r
- logln("formated: " +\r
- df.format(n, new StringBuffer(), new FieldPosition(0)));\r
- logln("expected: " + bigN.toString());\r
- }\r
- /**\r
- * DecimalFormat.format incorrectly formats -0.0.\r
- */\r
- public void Test4106667()\r
- {\r
- Locale savedLocale = Locale.getDefault();\r
- Locale.setDefault(Locale.US);\r
- DecimalFormat df = new DecimalFormat();\r
- df.setPositivePrefix("+");\r
- double d = -0.0;\r
- logln("pattern: \"" + df.toPattern() + "\"");\r
- StringBuffer buffer = new StringBuffer();\r
- df.format(d, buffer, new FieldPosition(0));\r
- if (!buffer.toString().equals("-0")) { // Corrected; see 4147706\r
- errln(d + " is formatted as " + buffer);\r
- }\r
- Locale.setDefault(savedLocale);\r
- }\r
-\r
- /**\r
- * DecimalFormat.setMaximumIntegerDigits() works incorrectly.\r
- */\r
- public void Test4110936()\r
- {\r
- NumberFormat nf = NumberFormat.getInstance();\r
- nf.setMaximumIntegerDigits(128);\r
- logln("setMaximumIntegerDigits(128)");\r
- if (nf.getMaximumIntegerDigits() != 128)\r
- errln("getMaximumIntegerDigits() returns " +\r
- nf.getMaximumIntegerDigits());\r
- }\r
- \r
- /**\r
- * Locale data should use generic currency symbol\r
- *\r
- * 1) Make sure that all currency formats use the generic currency symbol.\r
- * 2) Make sure we get the same results using the generic symbol or a\r
- * hard-coded one.\r
- */\r
- public void Test4122840()\r
- {\r
- Locale[] locales = NumberFormat.getAvailableLocales();\r
- \r
- for (int i = 0; i < locales.length; i++) {\r
- UResourceBundle rb = UResourceBundle.getBundleInstance(ICUResourceBundle.ICU_BASE_NAME,locales[i]);\r
-\r
- //\r
- // Get the currency pattern for this locale. We have to fish it\r
- // out of the ResourceBundle directly, since DecimalFormat.toPattern\r
- // will return the localized symbol, not \00a4\r
- //\r
- UResourceBundle numPatterns = rb.get("NumberPatterns");\r
- String pattern = numPatterns.getString(1);\r
- \r
- if (pattern.indexOf('\u00A4') == -1 ) { // 'x' not "x" -- workaround bug in IBM JDK 1.4.1\r
- errln("Currency format for " + locales[i] +\r
- " does not contain generic currency symbol:" +\r
- pattern );\r
- }\r
- \r
- // Create a DecimalFormat using the pattern we got and format a number\r
- DecimalFormatSymbols symbols = new DecimalFormatSymbols(locales[i]);\r
- DecimalFormat fmt1 = new DecimalFormat(pattern, symbols);\r
- \r
- String result1 = fmt1.format(1.111);\r
- \r
- //\r
- // Now substitute in the locale's currency symbol and create another\r
- // pattern. Replace the decimal separator with the monetary separator.\r
- //\r
- //char decSep = symbols.getDecimalSeparator(); //The variable is never used\r
- char monSep = symbols.getMonetaryDecimalSeparator();\r
- StringBuffer buf = new StringBuffer(pattern);\r
- for (int j = 0; j < buf.length(); j++) {\r
- if (buf.charAt(j) == '\u00a4') {\r
- String cur = "'" + symbols.getCurrencySymbol() + "'";\r
- buf.replace(j, j+1, cur); \r
- j += cur.length() - 1;\r
- }\r
- }\r
- symbols.setDecimalSeparator(monSep);\r
- DecimalFormat fmt2 = new DecimalFormat(buf.toString(), symbols);\r
- \r
- String result2 = fmt2.format(1.111);\r
- \r
- // NOTE: en_IN is a special case (ChoiceFormat currency display name)\r
- if (!result1.equals(result2) &&\r
- !locales[i].toString().equals("en_IN")) {\r
- errln("Results for " + locales[i] + " differ: " +\r
- result1 + " vs " + result2);\r
- }\r
- }\r
- }\r
- \r
- /**\r
- * DecimalFormat.format() delivers wrong string.\r
- */\r
- public void Test4125885()\r
- {\r
- double rate = 12.34;\r
- DecimalFormat formatDec = new DecimalFormat ("000.00");\r
- logln("toPattern: " + formatDec.toPattern());\r
- String rateString= formatDec.format(rate);\r
- if (!rateString.equals("012.34"))\r
- errln("result : " + rateString + " expected : 012.34");\r
- rate = 0.1234;\r
- formatDec = null;\r
- formatDec = new DecimalFormat ("+000.00%;-000.00%");\r
- logln("toPattern: " + formatDec.toPattern());\r
- rateString= formatDec.format(rate);\r
- if (!rateString.equals("+012.34%"))\r
- errln("result : " + rateString + " expected : +012.34%");\r
- }\r
-\r
- /**\r
- **\r
- * DecimalFormat produces extra zeros when formatting numbers.\r
- */\r
- public void Test4134034() {\r
- DecimalFormat nf = new DecimalFormat("##,###,###.00");\r
- \r
- String f = nf.format(9.02);\r
- if (f.equals("9.02")) logln(f + " ok"); else errln("9.02 -> " + f + "; want 9.02");\r
-\r
- f = nf.format(0);\r
- if (f.equals(".00")) logln(f + " ok"); else errln("0 -> " + f + "; want .00");\r
- }\r
-\r
- /**\r
- * CANNOT REPRODUCE - This bug could not be reproduced. It may be\r
- * a duplicate of 4134034.\r
- *\r
- * JDK 1.1.6 Bug, did NOT occur in 1.1.5\r
- * Possibly related to bug 4125885.\r
- * \r
- * This class demonstrates a regression in version 1.1.6\r
- * of DecimalFormat class.\r
- * \r
- * 1.1.6 Results\r
- * Value 1.2 Format #.00 Result '01.20' !!!wrong\r
- * Value 1.2 Format 0.00 Result '001.20' !!!wrong\r
- * Value 1.2 Format 00.00 Result '0001.20' !!!wrong\r
- * Value 1.2 Format #0.0# Result '1.2'\r
- * Value 1.2 Format #0.00 Result '001.20' !!!wrong\r
- * \r
- * 1.1.5 Results\r
- * Value 1.2 Format #.00 Result '1.20'\r
- * Value 1.2 Format 0.00 Result '1.20'\r
- * Value 1.2 Format 00.00 Result '01.20'\r
- * Value 1.2 Format #0.0# Result '1.2'\r
- * Value 1.2 Format #0.00 Result '1.20'\r
- */\r
- public void Test4134300() {\r
- String[] DATA = {\r
- // Pattern Expected string\r
- "#.00", "1.20",\r
- "0.00", "1.20",\r
- "00.00", "01.20",\r
- "#0.0#", "1.2",\r
- "#0.00", "1.20",\r
- };\r
- for (int i=0; i<DATA.length; i+=2) {\r
- String result = new DecimalFormat(DATA[i]).format(1.2);\r
- if (!result.equals(DATA[i+1])) {\r
- errln("Fail: 1.2 x " + DATA[i] + " = " + result +\r
- "; want " + DATA[i+1]);\r
- }\r
- else {\r
- logln("Ok: 1.2 x " + DATA[i] + " = " + result);\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * Empty pattern produces double negative prefix.\r
- */\r
- public void Test4140009() {\r
- final double IN[] = { 123.456, -123.456 };\r
- final String OUT[] = { "123.456", "-123.456" };\r
- for (int i=0; i<2; ++i) {\r
- DecimalFormat f = null;\r
- switch (i) {\r
- case 0:\r
- f = new DecimalFormat("",\r
- new DecimalFormatSymbols(Locale.ENGLISH));\r
- break;\r
- case 1:\r
- f = new DecimalFormat("#.#",\r
- new DecimalFormatSymbols(Locale.ENGLISH));\r
- f.applyPattern("");\r
- break;\r
- }\r
- for (int j=0; j<2; ++j) {\r
- assertEquals("<empty pat " + i + ">.format(" + IN[j] + ")",\r
- OUT[j], f.format(IN[j]));\r
- }\r
- }\r
- }\r
-\r
-//#if defined(FOUNDATION10)\r
-//#else\r
- /**\r
- * BigDecimal numbers get their fractions truncated by NumberFormat.\r
- */\r
- public void Test4141750() {\r
- try {\r
- String str = "12345.67";\r
- java.math.BigDecimal bd = new java.math.BigDecimal(str);\r
- String sd = NumberFormat.getInstance(Locale.US).format(bd);\r
- if (!sd.endsWith("67")) errln("Fail: " + str + " x format -> " + sd);\r
- }\r
- catch (Exception e) {\r
- warnln(e.toString());\r
- //e.printStackTrace();\r
- }\r
- }\r
-//#endif\r
-\r
- /**\r
- * DecimalFormat toPattern() doesn't quote special characters or handle\r
- * single quotes.\r
- */\r
- public void Test4145457() {\r
- try {\r
- DecimalFormat nf = (DecimalFormat)NumberFormat.getInstance();\r
- DecimalFormatSymbols sym = nf.getDecimalFormatSymbols();\r
- sym.setDecimalSeparator('\'');\r
- nf.setDecimalFormatSymbols(sym);\r
- double pi = 3.14159;\r
-\r
- String[] PATS = { "#.00 'num''ber'", "''#.00''" };\r
-\r
- for (int i=0; i<PATS.length; ++i) {\r
- nf.applyPattern(PATS[i]);\r
- String out = nf.format(pi);\r
- String pat = nf.toPattern();\r
- double val = nf.parse(out).doubleValue();\r
- \r
- nf.applyPattern(pat);\r
- String out2 = nf.format(pi);\r
- String pat2 = nf.toPattern();\r
- double val2 = nf.parse(out2).doubleValue();\r
- \r
- if (!pat.equals(pat2))\r
- errln("Fail with \"" + PATS[i] + "\": Patterns should concur, \"" +\r
- pat + "\" vs. \"" + pat2 + "\"");\r
- else\r
- logln("Ok \"" + PATS[i] + "\" toPattern() -> \"" + pat + '"');\r
-\r
- if (val == val2 && out.equals(out2)) {\r
- logln("Ok " + pi + " x \"" + PATS[i] + "\" -> \"" +\r
- out + "\" -> " + val + " -> \"" +\r
- out2 + "\" -> " + val2);\r
- }\r
- else {\r
- errln("Fail " + pi + " x \"" + PATS[i] + "\" -> \"" +\r
- out + "\" -> " + val + " -> \"" +\r
- out2 + "\" -> " + val2);\r
- }\r
- }\r
- }\r
- catch (ParseException e) {\r
- errln("Fail: " + e);\r
- e.printStackTrace();\r
- }\r
- }\r
-\r
- /**\r
- * DecimalFormat.applyPattern() sets minimum integer digits incorrectly.\r
- * CANNOT REPRODUCE\r
- * This bug is a duplicate of 4139344, which is a duplicate of 4134300\r
- */\r
- public void Test4147295() {\r
- DecimalFormat sdf = new DecimalFormat();\r
- String pattern = "#,###";\r
- logln("Applying pattern \"" + pattern + "\"");\r
- sdf.applyPattern(pattern);\r
- int minIntDig = sdf.getMinimumIntegerDigits();\r
- if (minIntDig != 0) {\r
- errln("Test failed");\r
- errln(" Minimum integer digits : " + minIntDig);\r
- errln(" new pattern: " + sdf.toPattern());\r
- } else {\r
- logln("Test passed");\r
- logln(" Minimum integer digits : " + minIntDig);\r
- }\r
- }\r
-\r
- /**\r
- * DecimalFormat formats -0.0 as +0.0\r
- * See also older related bug 4106658, 4106667\r
- */\r
- public void Test4147706() {\r
- DecimalFormat df = new DecimalFormat("#,##0.0##");\r
- df.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.ENGLISH));\r
- double d1 = -0.0;\r
- double d2 = -0.0001;\r
- StringBuffer f1 = df.format(d1, new StringBuffer(), new FieldPosition(0));\r
- StringBuffer f2 = df.format(d2, new StringBuffer(), new FieldPosition(0));\r
- if (!f1.toString().equals("-0.0")) {\r
- errln(d1 + " x \"" + df.toPattern() + "\" is formatted as \"" + f1 + '"');\r
- }\r
- if (!f2.toString().equals("-0.0")) {\r
- errln(d2 + " x \"" + df.toPattern() + "\" is formatted as \"" + f2 + '"');\r
- }\r
- }\r
-\r
- /**\r
- * NumberFormat cannot format Double.MAX_VALUE\r
- */\r
- public void Test4162198() {\r
- double dbl = Double.MAX_VALUE;\r
- NumberFormat f = NumberFormat.getInstance();\r
- f.setMaximumFractionDigits(Integer.MAX_VALUE);\r
- f.setMaximumIntegerDigits(Integer.MAX_VALUE);\r
- String s = f.format(dbl);\r
- logln("The number " + dbl + " formatted to " + s);\r
- Number n = null;\r
- try {\r
- n = f.parse(s);\r
- } catch (java.text.ParseException e) {\r
- errln("Caught a ParseException:");\r
- e.printStackTrace();\r
- }\r
- logln("The string " + s + " parsed as " + n);\r
- if (n.doubleValue() != dbl) {\r
- errln("Round trip failure");\r
- }\r
- }\r
-\r
- /**\r
- * NumberFormat does not parse negative zero.\r
- */\r
- public void Test4162852() throws ParseException {\r
- for (int i=0; i<2; ++i) {\r
- NumberFormat f = (i == 0) ? NumberFormat.getInstance()\r
- : NumberFormat.getPercentInstance();\r
- double d = -0.0;\r
- String s = f.format(d);\r
- double e = f.parse(s).doubleValue();\r
- logln("" +\r
- d + " -> " +\r
- '"' + s + '"' + " -> " +\r
- e);\r
- if (e != 0.0 || 1.0/e > 0.0) {\r
- logln("Failed to parse negative zero");\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * NumberFormat truncates data\r
- */\r
- public void Test4167494() throws Exception {\r
- NumberFormat fmt = NumberFormat.getInstance(Locale.US);\r
- \r
- double a = Double.MAX_VALUE;\r
- String s = fmt.format(a);\r
- double b = fmt.parse(s).doubleValue();\r
- boolean match = a == b;\r
- if (match) {\r
- logln("" + a + " -> \"" + s + "\" -> " + b + " ok");\r
- } else {\r
- errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL");\r
- }\r
-\r
- // We don't test Double.MIN_VALUE because the locale data for the US\r
- // currently doesn't specify enough digits to display Double.MIN_VALUE.\r
- // This is correct for now; however, we leave this here as a reminder\r
- // in case we want to address this later.\r
- if (false) {\r
- a = Double.MIN_VALUE;\r
- s = fmt.format(a);\r
- b = fmt.parse(s).doubleValue();\r
- match = a == b;\r
- if (match) {\r
- logln("" + a + " -> \"" + s + "\" -> " + b + " ok");\r
- } else {\r
- errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL");\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * DecimalFormat.parse() fails when ParseIntegerOnly set to true\r
- */\r
- public void Test4170798() {\r
- Locale savedLocale = Locale.getDefault();\r
- Locale.setDefault(Locale.US);\r
- DecimalFormat df = new DecimalFormat();\r
- df.setParseIntegerOnly(true);\r
- Number n = df.parse("-0.0", new ParsePosition(0));\r
- if (!(n instanceof Double)\r
- || n.intValue() != 0) {\r
- errln("FAIL: parse(\"-0.0\") returns " +\r
- n + " (" + n.getClass().getName() + ')');\r
- }\r
- Locale.setDefault(savedLocale);\r
- }\r
-\r
- /**\r
- * toPattern only puts the first grouping separator in.\r
- */\r
- public void Test4176114() {\r
- String[] DATA = {\r
- "00", "#00",\r
- "000", "#000", // No grouping\r
- "#000", "#000", // No grouping\r
- "#,##0", "#,##0",\r
- "#,000", "#,000",\r
- "0,000", "#0,000",\r
- "00,000", "#00,000",\r
- "000,000", "#,000,000",\r
- "0,000,000,000,000.0000", "#0,000,000,000,000.0000", // Reported\r
- };\r
- for (int i=0; i<DATA.length; i+=2) {\r
- DecimalFormat df = new DecimalFormat(DATA[i]);\r
- String s = df.toPattern();\r
- if (!s.equals(DATA[i+1])) {\r
- errln("FAIL: " + DATA[i] + " -> " + s + ", want " + DATA[i+1]);\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * DecimalFormat is incorrectly rounding numbers like 1.2501 to 1.2\r
- */\r
- public void Test4179818() {\r
- String DATA[] = {\r
- // Input Pattern Expected output\r
- "1.2511", "#.#", "1.3",\r
- "1.2501", "#.#", "1.3",\r
- "0.9999", "#", "1",\r
- };\r
- DecimalFormat fmt = new DecimalFormat("#",\r
- new DecimalFormatSymbols(Locale.US));\r
- for (int i=0; i<DATA.length; i+=3) {\r
- double in = Double.valueOf(DATA[i]).doubleValue();\r
- String pat = DATA[i+1];\r
- String exp = DATA[i+2];\r
- fmt.applyPattern(pat);\r
- String out = fmt.format(in);\r
- if (out.equals(exp)) {\r
- logln("Ok: " + in + " x " + pat + " = " + out);\r
- } else {\r
- errln("FAIL: " + in + " x " + pat + " = " + out +\r
- ", expected " + exp);\r
- }\r
- }\r
- }\r
-\r
- public void Test4185761() throws IOException, ClassNotFoundException {\r
- ByteArrayOutputStream baos = new ByteArrayOutputStream();\r
- ObjectOutputStream oos = new ObjectOutputStream(baos);\r
- \r
- NumberFormat nf = NumberFormat.getInstance(Locale.US);\r
-\r
- // Set special values we are going to search for in the output byte stream\r
- // These are all legal values.\r
- nf.setMinimumIntegerDigits(0x111); // Keep under 309\r
- nf.setMaximumIntegerDigits(0x112); // Keep under 309\r
- nf.setMinimumFractionDigits(0x113); // Keep under 340\r
- nf.setMaximumFractionDigits(0x114); // Keep under 340\r
- \r
- oos.writeObject(nf);\r
- oos.flush();\r
- baos.close();\r
- \r
- byte[] bytes = baos.toByteArray();\r
-\r
- // Scan for locations of min/max int/fract values in the byte array.\r
- // At the moment (ICU4J 2.1), there is only one instance of each target pair\r
- // in the byte stream, so assume first match is it. Note this is not entirely\r
- // failsafe, and needs to be checked if we change the package or structure of\r
- // this class.\r
- // Current positions are 890, 880, 886, 876\r
- int[] offsets = new int[4];\r
- for (int i = 0; i < bytes.length - 1; ++i) {\r
- if (bytes[i] == 0x01) { // high byte\r
- for (int j = 0; j < offsets.length; ++j) {\r
- if ((offsets[j] == 0) && (bytes[i+1] == (0x11 + j))) { // low byte\r
- offsets[j] = i;\r
- break;\r
- }\r
- }\r
- }\r
- }\r
-\r
- {\r
- ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));\r
- Object o = ois.readObject();\r
- ois.close();\r
- \r
- if (!nf.equals(o)) {\r
- errln("Fail: NumberFormat serialization/equality bug");\r
- } else {\r
- logln("NumberFormat serialization/equality is OKAY.");\r
- }\r
- }\r
-\r
- // Change the values in the byte stream so that min > max.\r
- // Numberformat should catch this and throw an exception.\r
- for (int i = 0; i < offsets.length; ++i) {\r
- bytes[offsets[i]] = (byte)(4 - i);\r
- }\r
-\r
- {\r
- ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));\r
- try {\r
- NumberFormat format = (NumberFormat) ois.readObject();\r
- logln("format: " + format.format(1234.56)); //fix "The variable is never used"\r
- errln("FAIL: Deserialized bogus NumberFormat with minXDigits > maxXDigits");\r
- } catch (InvalidObjectException e) {\r
- logln("Ok: " + e.getMessage());\r
- }\r
- }\r
-\r
- // Set values so they are too high, but min <= max\r
- // Format should pass the min <= max test, and DecimalFormat should reset to current maximum\r
- // (for compatibility with versions streamed out before the maximums were imposed).\r
- for (int i = 0; i < offsets.length; ++i) {\r
- bytes[offsets[i]] = 4;\r
- }\r
-\r
- {\r
- ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));\r
- NumberFormat format = (NumberFormat) ois.readObject();\r
- //For compatibility with previous version\r
- if ((format.getMaximumIntegerDigits() != 309) \r
- || format.getMaximumFractionDigits() != 340) {\r
- errln("FAIL: Deserialized bogus NumberFormat with values out of range," +\r
- " intMin: " + format.getMinimumIntegerDigits() +\r
- " intMax: " + format.getMaximumIntegerDigits() +\r
- " fracMin: " + format.getMinimumFractionDigits() +\r
- " fracMax: " + format.getMaximumFractionDigits());\r
- } else {\r
- logln("Ok: Digit count out of range");\r
- }\r
- }\r
- }\r
-\r
-\r
- /**\r
- * Some DecimalFormatSymbols changes are not picked up by DecimalFormat.\r
- * This includes the minus sign, currency symbol, international currency\r
- * symbol, percent, and permille. This is filed as bugs 4212072 and\r
- * 4212073.\r
- */\r
- public void Test4212072() throws IOException, ClassNotFoundException {\r
- DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);\r
- DecimalFormat fmt = new DecimalFormat("#", sym);\r
-\r
- sym.setMinusSign('^');\r
- fmt.setDecimalFormatSymbols(sym);\r
- if (!fmt.format(-1).equals("^1")) {\r
- errln("FAIL: -1 x (minus=^) -> " + fmt.format(-1) +\r
- ", exp ^1");\r
- }\r
- if (!fmt.getNegativePrefix().equals("^")) {\r
- errln("FAIL: (minus=^).getNegativePrefix -> " +\r
- fmt.getNegativePrefix() + ", exp ^");\r
- }\r
- sym.setMinusSign('-');\r
-\r
- fmt.applyPattern("#%");\r
- sym.setPercent('^');\r
- fmt.setDecimalFormatSymbols(sym);\r
- if (!fmt.format(0.25).equals("25^")) {\r
- errln("FAIL: 0.25 x (percent=^) -> " + fmt.format(0.25) +\r
- ", exp 25^");\r
- }\r
- if (!fmt.getPositiveSuffix().equals("^")) {\r
- errln("FAIL: (percent=^).getPositiveSuffix -> " +\r
- fmt.getPositiveSuffix() + ", exp ^");\r
- }\r
- sym.setPercent('%');\r
- \r
- fmt.applyPattern("#\u2030");\r
- sym.setPerMill('^');\r
- fmt.setDecimalFormatSymbols(sym);\r
- if (!fmt.format(0.25).equals("250^")) {\r
- errln("FAIL: 0.25 x (permill=^) -> " + fmt.format(0.25) +\r
- ", exp 250^");\r
- }\r
- if (!fmt.getPositiveSuffix().equals("^")) {\r
- errln("FAIL: (permill=^).getPositiveSuffix -> " +\r
- fmt.getPositiveSuffix() + ", exp ^");\r
- }\r
- sym.setPerMill('\u2030');\r
-\r
- fmt.applyPattern("\u00A4#.00");\r
- sym.setCurrencySymbol("usd");\r
- fmt.setDecimalFormatSymbols(sym);\r
- if (!fmt.format(12.5).equals("usd12.50")) {\r
- errln("FAIL: 12.5 x (currency=usd) -> " + fmt.format(12.5) +\r
- ", exp usd12.50");\r
- }\r
- if (!fmt.getPositivePrefix().equals("usd")) {\r
- errln("FAIL: (currency=usd).getPositivePrefix -> " +\r
- fmt.getPositivePrefix() + ", exp usd");\r
- }\r
- sym.setCurrencySymbol("$");\r
-\r
- fmt.applyPattern("\u00A4\u00A4#.00");\r
- sym.setInternationalCurrencySymbol("DOL");\r
- fmt.setDecimalFormatSymbols(sym);\r
- if (!fmt.format(12.5).equals("DOL12.50")) {\r
- errln("FAIL: 12.5 x (intlcurrency=DOL) -> " + fmt.format(12.5) +\r
- ", exp DOL12.50");\r
- }\r
- if (!fmt.getPositivePrefix().equals("DOL")) {\r
- errln("FAIL: (intlcurrency=DOL).getPositivePrefix -> " +\r
- fmt.getPositivePrefix() + ", exp DOL");\r
- }\r
- sym.setInternationalCurrencySymbol("USD");\r
-\r
- if (VersionInfo.ICU_VERSION == VersionInfo.getInstance(2,2)) {\r
- // bug in 2.2 that fails this test\r
- // to be fixed in the later versions\r
- System.out.println("\n Test skipped for release 2.2");\r
- return;\r
- }\r
- \r
- // Since the pattern logic has changed, make sure that patterns round\r
- // trip properly. Test stream in/out integrity too.\r
- Locale[] avail = NumberFormat.getAvailableLocales();\r
- for (int i=0; i<avail.length; ++i) {\r
- for (int j=0; j<3; ++j) {\r
- NumberFormat nf;\r
- switch (j) {\r
- case 0:\r
- nf = NumberFormat.getInstance(avail[i]);\r
- break;\r
- case 1:\r
- nf = NumberFormat.getCurrencyInstance(avail[i]);\r
- break;\r
- default:\r
- nf = NumberFormat.getPercentInstance(avail[i]);\r
- break;\r
- }\r
- DecimalFormat df = (DecimalFormat) nf;\r
- \r
- // Test toPattern/applyPattern round trip\r
- String pat = df.toPattern();\r
- DecimalFormatSymbols symb = new DecimalFormatSymbols(avail[i]);\r
- DecimalFormat f2 = new DecimalFormat(pat, symb);\r
- if (!df.equals(f2)) {\r
- errln("FAIL: " + avail[i] + " #" + j + " -> \"" + pat +\r
- "\" -> \"" + f2.toPattern() + '"');\r
- }\r
-\r
- // Test toLocalizedPattern/applyLocalizedPattern round trip\r
- pat = df.toLocalizedPattern();\r
- try{\r
- f2.applyLocalizedPattern(pat);\r
- \r
- String s1 = f2.format(123456);\r
- String s2 = df.format(123456);\r
- if(!s1.equals(s2)){\r
- errln("FAIL: " + avail[i] + " #" + j + " -> localized \"" + s2 +\r
- "\" -> \"" + s2 + '"'+ " in locale "+df.getLocale(ULocale.ACTUAL_LOCALE));\r
- \r
- }\r
- if (!df.equals(f2)) {\r
- errln("FAIL: " + avail[i] + " #" + j + " -> localized \"" + pat +\r
- "\" -> \"" + f2.toLocalizedPattern() + '"'+ " in locale "+df.getLocale(ULocale.ACTUAL_LOCALE));\r
- errln("s1: "+s1+" s2: "+s2);\r
- }\r
- \r
- }catch(IllegalArgumentException ex){\r
- errln(ex.getMessage()+" for locale "+ df.getLocale(ULocale.ACTUAL_LOCALE));\r
- }\r
- \r
-\r
- // Test writeObject/readObject round trip\r
- ByteArrayOutputStream baos = new ByteArrayOutputStream();\r
- ObjectOutputStream oos = new ObjectOutputStream(baos);\r
- oos.writeObject(df);\r
- oos.flush();\r
- baos.close();\r
- byte[] bytes = baos.toByteArray();\r
- ObjectInputStream ois =\r
- new ObjectInputStream(new ByteArrayInputStream(bytes));\r
- f2 = (DecimalFormat) ois.readObject();\r
- if (!df.equals(f2)) {\r
- errln("FAIL: Stream in/out " + avail[i] + " -> \"" + pat +\r
- "\" -> " +\r
- (f2 != null ? ("\""+f2.toPattern()+'"') : "null"));\r
- }\r
-\r
- }\r
- }\r
-\r
- // @since ICU 2.4\r
- // Make sure that all special characters, when quoted in a suffix or\r
- // prefix, lose their special meaning.\r
- char[] SPECIALS = { '0', ',', '.', '\u2030', '%', '#',\r
- ';', 'E', '*', '+', '-' };\r
- sym = new DecimalFormatSymbols(Locale.US);\r
- for (int j=0; j<SPECIALS.length; ++j) {\r
- char special = SPECIALS[j];\r
- String pat = "'" + special + "'#0'" + special + "'";\r
- try {\r
- fmt = new DecimalFormat(pat, sym);\r
- String pat2 = fmt.toPattern();\r
- if (!pat.equals(pat2)) {\r
- errln("FAIL: Pattern \"" + pat + "\" => toPattern() => \"" +\r
- pat2 + "\"");\r
- }\r
- String s = fmt.format(123);\r
- String exp = "" + special + "123" + special;\r
- if (!s.equals(exp)) {\r
- errln("FAIL: 123 x \"" + pat + "\" => \"" + s + "\", exp \"" +\r
- exp + "\"");\r
- }\r
- } catch (IllegalArgumentException e) {\r
- errln("FAIL: Pattern \"" + pat + "\" => " + e.getMessage());\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * DecimalFormat.parse() fails for mulipliers 2^n.\r
- */\r
- public void Test4216742() throws ParseException {\r
- DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance(Locale.US);\r
- long[] DATA = { Long.MIN_VALUE, Long.MAX_VALUE, -100000000L, 100000000L};\r
- for (int i=0; i<DATA.length; ++i) {\r
- String str = Long.toString(DATA[i]);\r
- for (int m = 1; m <= 100; m++) {\r
- fmt.setMultiplier(m);\r
- long n = ((Number) fmt.parse(str)).longValue();\r
- if (n > 0 != DATA[i] > 0) {\r
- errln("\"" + str + "\" parse(x " + fmt.getMultiplier() +\r
- ") => " + n);\r
- }\r
- }\r
- }\r
- }\r
-\r
- /**\r
- * DecimalFormat formats 1.001 to "1.00" instead of "1" with 2 fraction\r
- * digits.\r
- */\r
- public void Test4217661() {\r
- Object[] DATA = {\r
- new Double(0.001), "0",\r
- new Double(1.001), "1",\r
- new Double(0.006), "0.01",\r
- new Double(1.006), "1.01",\r
- };\r
- NumberFormat fmt = NumberFormat.getInstance(Locale.US);\r
- fmt.setMaximumFractionDigits(2); \r
- for (int i=0; i<DATA.length; i+=2) {\r
- String s = fmt.format(((Double) DATA[i]).doubleValue());\r
- if (!s.equals(DATA[i+1])) {\r
- errln("FAIL: Got " + s + ", exp " + DATA[i+1]); \r
- }\r
- }\r
- }\r
- \r
- /**\r
- * 4243011: Formatting .5 rounds to "1" instead of "0"\r
- */\r
- public void Test4243011() {\r
- double DATA[] = {0.5, 1.5, 2.5, 3.5, 4.5};\r
- String EXPECTED[] = {"0.", "2.", "2.", "4.", "4."};\r
- \r
- DecimalFormat format = new DecimalFormat("0.");\r
- for (int i = 0; i < DATA.length; i++) {\r
- String result = format.format(DATA[i]);\r
- if (result.equals(EXPECTED[i])) {\r
- logln("OK: got " + result);\r
- } else {\r
- errln("FAIL: got " + result);\r
- }\r
- }\r
- }\r
- \r
- /**\r
- * 4243108: format(0.0) gives "0.1" if preceded by parse("99.99")\r
- */\r
- public void Test4243108() {\r
- DecimalFormat f = new DecimalFormat("#.#");\r
- String result = f.format(0.0);\r
- if (result.equals("0")) {\r
- logln("OK: got " + result);\r
- } else {\r
- errln("FAIL: got " + result);\r
- }\r
- try {\r
- double dResult = f.parse("99.99").doubleValue();\r
- if (dResult == 99.99) {\r
- logln("OK: got " + dResult);\r
- } else {\r
- errln("FAIL: got " + dResult);\r
- }\r
- } catch (ParseException e) {\r
- errln("Caught a ParseException:");\r
- e.printStackTrace();\r
- } \r
- result = f.format(0.0);\r
- if (result.equals("0")) {\r
- logln("OK: got " + result);\r
- } else {\r
- errln("FAIL: got " + result);\r
- }\r
- }\r
- \r
- /**\r
- * 4330377: DecimalFormat engineering notation gives incorrect results\r
- */\r
- public void test4330377() {\r
- /*\r
- double[] input = {5000.0, 500.0, 50.0, 5.0, 0.5, 0.05, 0.005, 0.0005,\r
- 5050.0, 505.0, 50.5, 5.05, 0.505, 0.0505, 0.00505, 0.000505};\r
- String[] pattern = {"000.#E0", "##0.#E0", "#00.#E0"};\r
- String[][] expected = {\r
- // it's questionable whether "#00.#E0" should result in post-decimal\r
- // zeroes, i.e., whether "5.0E3", "5.0E0", "5.0E-3" are really good\r
- {"500E1", "5E3", "5.0E3"},\r
- {"500E0", "500E0", "500E0"},\r
- {"500E-1", "50E0", "50E0"},\r
- {"500E-2", "5E0", "5.0E0"},\r
- {"500E-3", "500E-3", "500E-3"},\r
- {"500E-4", "50E-3", "50E-3"},\r
- {"500E-5", "5E-3", "5.0E-3"},\r
- {"500E-6", "500E-6", "500E-6"},\r
- {"505E1", "5.05E3", "5.05E3"},\r
- {"505E0", "505E0", "505E0"},\r
- {"505E-1", "50.5E0", "50.5E0"},\r
- {"505E-2", "5.05E0", "5.05E0"},\r
- {"505E-3", "505E-3", "505E-3"},\r
- {"505E-4", "50.5E-3", "50.5E-3"},\r
- {"505E-5", "5.05E-3", "5.05E-3"},\r
- {"505E-6", "505E-6", "505E-6"}\r
- };\r
- for (int i = 0; i < input.length; i++) {\r
- for (int j = 0; j < pattern.length; j++) {\r
- DecimalFormat format = new DecimalFormat(pattern[j]);\r
- String result = format.format(input[i]);\r
- if (!result.equals(expected[i][j])) {\r
- errln("FAIL: input: " + input[i] +\r
- ", pattern: " + pattern[j] +\r
- ", expected: " + expected[i][j] +\r
- ", got: " + result);\r
- }\r
- }\r
- }\r
- */\r
- }\r
- \r
- /**\r
- * 4233840: NumberFormat does not round correctly\r
- */\r
- public void test4233840() {\r
- float f = 0.0099f;\r
-\r
- NumberFormat nf = new DecimalFormat("0.##", new DecimalFormatSymbols(Locale.US));\r
- nf.setMinimumFractionDigits(2);\r
- \r
- String result = nf.format(f);\r
- \r
- if (!result.equals("0.01")) {\r
- errln("FAIL: input: " + f + ", expected: 0.01, got: " + result);\r
- }\r
- }\r
- \r
- /**\r
- * 4241880: Decimal format doesnt round a double properly when the number is less than 1\r
- */\r
- public void test4241880() {\r
- Locale savedLocale = Locale.getDefault();\r
- Locale.setDefault(Locale.US);\r
- double[] input = {\r
- .019, .009, .015, .016, .014,\r
- .004, .005, .006, .007, .008,\r
- .5, 1.5, .05, .15, .005,\r
- .015, .0005, .0015,\r
- };\r
- String[] pattern = {\r
- "##0%", "##0%", "##0%", "##0%", "##0%",\r
- "##0%", "##0%", "##0%", "##0%", "##0%",\r
- "#,##0", "#,##0", "#,##0.0", "#,##0.0", "#,##0.00",\r
- "#,##0.00", "#,##0.000", "#,##0.000",\r
- };\r
- String[] expected = {\r
- "2%", "1%", "2%", "2%", "1%",\r
- "0%", "0%", "1%", "1%", "1%",\r
- "0", "2", "0.0", "0.2", "0.00",\r
- "0.02", "0.000", "0.002",\r
- };\r
- for (int i = 0; i < input.length; i++) {\r
- DecimalFormat format = new DecimalFormat(pattern[i]);\r
- String result = format.format(input[i]);\r
- if (!result.equals(expected[i])) {\r
- errln("FAIL: input: " + input[i] +\r
- ", pattern: " + pattern[i] +\r
- ", expected: " + expected[i] +\r
- ", got: " + result);\r
- }\r
- }\r
- Locale.setDefault(savedLocale);\r
- }\r
-}\r
-\r
-class myformat implements Serializable\r
-{\r
- /**\r
- * For serialization\r
- */\r
- private static final long serialVersionUID = 4120813612616076506L;\r
- DateFormat _dateFormat = DateFormat.getDateInstance();\r
-\r
- public String Now()\r
- {\r
- GregorianCalendar calendar = new GregorianCalendar();\r
- Date t = calendar.getTime();\r
- String nowStr = _dateFormat.format(t);\r
- return nowStr;\r
- }\r
-}\r
-\r
-class MyNumberFormatTest extends NumberFormat {\r
- /**\r
- * For serialization\r
- */\r
- private static final long serialVersionUID = 1251303884737169952L;\r
- public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {\r
- return new StringBuffer("");\r
- }\r
- public StringBuffer format(long number,StringBuffer toAppendTo, FieldPosition pos) {\r
- return new StringBuffer("");\r
- }\r
- public Number parse(String text, ParsePosition parsePosition) {\r
- return new Integer(0);\r
- }\r
-//#if defined(FOUNDATION10)\r
-//#else\r
- public StringBuffer format(java.math.BigDecimal number, StringBuffer toAppendTo, FieldPosition pos) {\r
- return new StringBuffer("");\r
- }\r
-//#endif\r
- public StringBuffer format(BigInteger number, StringBuffer toAppendTo, FieldPosition pos) {\r
- return new StringBuffer("");\r
- }\r
- public StringBuffer format(com.ibm.icu.math.BigDecimal number, StringBuffer toAppendTo, FieldPosition pos) {\r
- return new StringBuffer("");\r
- }\r
-}\r
-\r
+//##header J2SE15
+/*****************************************************************************************
+ *
+ * Copyright (C) 1996-2009, International Business Machines
+ * Corporation and others. All Rights Reserved.
+ **/
+
+/**
+ * Port From: JDK 1.4b1 : java.text.Format.NumberRegression
+ * Source File: java/text/format/NumberRegression.java
+ **/
+
+/**
+ * @test 1.49 01/05/21
+ * @bug 4052223 4059870 4061302 4062486 4066646 4068693 4070798 4071005 4071014
+ * 4071492 4071859 4074454 4074620 4075713 4083018 4086575 4087244 4087245
+ * 4087251 4087535 4088161 4088503 4090489 4090504 4092480 4092561 4095713
+ * 4098741 4099404 4101481 4106658 4106662 4106664 4108738 4110936 4122840
+ * 4125885 4134034 4134300 4140009 4141750 4145457 4147295 4147706 4162198
+ * 4162852 4167494 4170798 4176114 4179818 4185761 4212072 4212073 4216742
+ * 4217661 4243011 4243108 4330377 4233840
+ * @summary Regression tests for NumberFormat and associated classes
+ */
+
+package com.ibm.icu.dev.test.format;
+
+//import com.ibm.icu.impl.ICULocaleData;
+import com.ibm.icu.impl.ICUResourceBundle;
+import com.ibm.icu.text.*;
+import com.ibm.icu.util.*;
+
+import java.io.*;
+import java.math.BigInteger;
+import java.text.FieldPosition;
+import java.text.ParseException;
+import java.text.ParsePosition;
+import java.util.Date;
+import java.util.Locale;
+
+public class NumberRegression extends com.ibm.icu.dev.test.TestFmwk {
+
+ public static void main(String[] args) throws Exception {
+ new NumberRegression().run(args);
+ }
+
+ private static final char EURO = '\u20ac';
+
+ /**
+ * NumberFormat.equals comparing with null should always return false.
+ */
+ public void Test4075713(){
+
+ try {
+ MyNumberFormatTest tmp = new MyNumberFormatTest();
+ if (!tmp.equals(null))
+ logln("NumberFormat.equals passed");
+ } catch (NullPointerException e) {
+ errln("(new MyNumberFormatTest()).equals(null) throws unexpected exception");
+ }
+ }
+
+ /**
+ * NumberFormat.equals comparing two obj equal even the setGroupingUsed
+ * flag is different.
+ */
+ public void Test4074620() {
+
+ MyNumberFormatTest nf1 = new MyNumberFormatTest();
+ MyNumberFormatTest nf2 = new MyNumberFormatTest();
+
+ nf1.setGroupingUsed(false);
+ nf2.setGroupingUsed(true);
+
+ if (nf1.equals(nf2)) errln("Test for bug 4074620 failed");
+ else logln("Test for bug 4074620 passed.");
+ return;
+ }
+
+
+ /**
+ * DecimalFormat.format() incorrectly uses maxFractionDigits setting.
+ */
+
+ public void Test4088161 (){
+ DecimalFormat df = new DecimalFormat();
+ double d = 100;
+ df.setMinimumFractionDigits(0);
+ df.setMaximumFractionDigits(16);
+ StringBuffer sBuf1 = new StringBuffer("");
+ FieldPosition fp1 = new FieldPosition(0);
+ logln("d = " + d);
+ logln("maxFractionDigits = " + df.getMaximumFractionDigits());
+ logln(" format(d) = '" + df.format(d, sBuf1, fp1) + "'");
+ df.setMaximumFractionDigits(17);
+ StringBuffer sBuf2 = new StringBuffer("");
+ FieldPosition fp2 = new FieldPosition(0);
+ logln("maxFractionDigits = " + df.getMaximumFractionDigits());
+ df.format(d, sBuf2, fp2);
+ if (!sBuf2.toString().equals("100"))
+ errln(" format(d) = '" + sBuf2 + "'");
+ }
+ /**
+ * DecimalFormatSymbols should be cloned in the ctor DecimalFormat.
+ * DecimalFormat(String, DecimalFormatSymbols).
+ */
+ public void Test4087245 (){
+ DecimalFormatSymbols symbols = new DecimalFormatSymbols();
+ DecimalFormat df = new DecimalFormat("#,##0.0", symbols);
+ long n = 123;
+ StringBuffer buf1 = new StringBuffer();
+ StringBuffer buf2 = new StringBuffer();
+ logln("format(" + n + ") = " +
+ df.format(n, buf1, new FieldPosition(0)));
+ symbols.setDecimalSeparator('p'); // change value of field
+ logln("format(" + n + ") = " +
+ df.format(n, buf2, new FieldPosition(0)));
+ if (!buf1.toString().equals(buf2.toString()))
+ errln("Test for bug 4087245 failed");
+ }
+ /**
+ * DecimalFormat.format() incorrectly formats 0.0
+ */
+ public void Test4087535 ()
+ {
+ DecimalFormat df = new DecimalFormat();
+ df.setMinimumIntegerDigits(0);
+
+ double n = 0;
+ String buffer = new String();
+ buffer = df.format(n);
+ if (buffer.length() == 0)
+ errln(n + ": '" + buffer + "'");
+ n = 0.1;
+ buffer = df.format(n);
+ if (buffer.length() == 0)
+ errln(n + ": '" + buffer + "'");
+ }
+
+ /**
+ * DecimalFormat.format fails when groupingSize is set to 0.
+ */
+ public void Test4088503 (){
+ DecimalFormat df = new DecimalFormat();
+ df.setGroupingSize(0);
+ StringBuffer sBuf = new StringBuffer("");
+ FieldPosition fp = new FieldPosition(0);
+ try {
+ logln(df.format(123, sBuf, fp).toString());
+ } catch (Exception foo) {
+ errln("Test for bug 4088503 failed.");
+ }
+
+ }
+ /**
+ * NumberFormat.getCurrencyInstance is wrong.
+ */
+ public void Test4066646 () {
+ //float returnfloat = 0.0f; //The variable is never used
+ assignFloatValue(2.04f);
+ assignFloatValue(2.03f);
+ assignFloatValue(2.02f);
+ assignFloatValue(0.0f);
+ }
+
+ public float assignFloatValue(float returnfloat)
+ {
+ logln(" VALUE " + returnfloat);
+ NumberFormat nfcommon = NumberFormat.getCurrencyInstance(Locale.US);
+ nfcommon.setGroupingUsed(false);
+
+ String stringValue = nfcommon.format(returnfloat).substring(1);
+ if (Float.valueOf(stringValue).floatValue() != returnfloat)
+ errln(" DISPLAYVALUE " + stringValue);
+ return returnfloat;
+ } // End Of assignFloatValue()
+
+ /**
+ * DecimalFormat throws exception when parsing "0"
+ */
+ public void Test4059870() {
+ DecimalFormat format = new DecimalFormat("00");
+ try {
+ logln(format.parse("0").toString());
+ } catch (Exception e) { errln("Test for bug 4059870 failed : " + e); }
+ }
+ /**
+ * DecimalFormatSymbol.equals should always return false when
+ * comparing with null.
+ */
+
+ public void Test4083018 (){
+ DecimalFormatSymbols dfs = new DecimalFormatSymbols();
+ try {
+ if (!dfs.equals(null))
+ logln("Test Passed!");
+ } catch (Exception foo) {
+ errln("Test for bug 4083018 failed => Message : " + foo.getMessage());
+ }
+ }
+ /**
+ * DecimalFormat does not round up correctly.
+ */
+ public void Test4071492 (){
+ double x = 0.00159999;
+ NumberFormat nf = NumberFormat.getInstance();
+ nf.setMaximumFractionDigits(4);
+ String out = nf.format(x);
+ logln("0.00159999 formats with 4 fractional digits to " + out);
+ String expected = "0.0016";
+ if (!out.equals(expected))
+ errln("FAIL: Expected " + expected);
+ }
+
+ /**
+ * A space as a group separator for localized pattern causes
+ * wrong format. WorkAround : use non-breaking space.
+ */
+ public void Test4086575() {
+
+ NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE);
+ logln("nf toPattern1: " + ((DecimalFormat)nf).toPattern());
+ logln("nf toLocPattern1: " + ((DecimalFormat)nf).toLocalizedPattern());
+
+ // No group separator
+ logln("...applyLocalizedPattern ###,00;(###,00) ");
+ ((DecimalFormat)nf).applyLocalizedPattern("###,00;(###,00)");
+ logln("nf toPattern2: " + ((DecimalFormat)nf).toPattern());
+ logln("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern());
+
+ logln("nf: " + nf.format(1234)); // 1234,00
+ logln("nf: " + nf.format(-1234)); // (1234,00)
+
+ // Space as group separator
+
+ logln("...applyLocalizedPattern # ###,00;(# ###,00) ");
+ ((DecimalFormat)nf).applyLocalizedPattern("#\u00a0###,00;(#\u00a0###,00)");
+ logln("nf toPattern2: " + ((DecimalFormat)nf).toPattern());
+ logln("nf toLocPattern2: " + ((DecimalFormat)nf).toLocalizedPattern());
+ String buffer = nf.format(1234);
+ if (!buffer.equals("1\u00a0234,00"))
+ errln("nf : " + buffer); // Expect 1 234,00
+ buffer = nf.format(-1234);
+ if (!buffer.equals("(1\u00a0234,00)"))
+ errln("nf : " + buffer); // Expect (1 234,00)
+
+ // Erroneously prints:
+ // 1234,00 ,
+ // (1234,00 ,)
+
+ }
+ /**
+ * DecimalFormat.parse returns wrong value
+ */
+ public void Test4068693()
+ {
+ logln("----- Test Application -----");
+ //ParsePosition pos;
+ DecimalFormat df = new DecimalFormat();
+ Number d = df.parse("123.55456", new ParsePosition(0));
+ if (!d.toString().equals("123.55456")) {
+ errln("Result -> " + d.doubleValue());
+ }
+ }
+
+ /* bugs 4069754, 4067878
+ * null pointer thrown when accessing a deserialized DecimalFormat
+ * object.
+ */
+ public void Test4069754() throws Exception
+ {
+ //try {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ myformat it = new myformat();
+ logln(it.Now());
+ oos.writeObject(it);
+ oos.flush();
+ baos.close();
+ logln("Save OK!");
+ byte [] bytes = baos.toByteArray();
+ ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
+ myformat o = (myformat)ois.readObject();
+ ois.close();
+ it.Now();
+ logln("Load OK!");
+ if (!o._dateFormat.equals(it._dateFormat)) {
+ throw new Exception("The saved and loaded object are not equals!");
+ }
+ logln("Compare OK!");
+ //} catch (Exception foo) {
+ //errln("Test for bug 4069754 or 4057878 failed => Exception: " + foo.getMessage());
+ //}
+ }
+
+ /**
+ * DecimalFormat.applyPattern(String) allows illegal patterns
+ */
+ public void Test4087251 (){
+ DecimalFormat df = new DecimalFormat();
+ try {
+ df.applyPattern("#.#.#");
+ logln("toPattern() returns \"" + df.toPattern() + "\"");
+ errln("applyPattern(\"#.#.#\") doesn't throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ logln("Caught Illegal Argument Error !");
+ }
+ // Second test; added 5/11/98 when reported to fail on 1.2b3
+ try {
+ df.applyPattern("#0.0#0#0");
+ logln("toPattern() returns \"" + df.toPattern() + "\"");
+ errln("applyPattern(\"#0.0#0#0\") doesn't throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ logln("Ok - IllegalArgumentException for #0.0#0#0");
+ }
+ }
+
+ /**
+ * DecimalFormat.format() loses precision
+ */
+ public void Test4090489 (){
+ DecimalFormat df = new DecimalFormat();
+ df.setMinimumFractionDigits(10);
+ df.setGroupingUsed(false);
+ double d = 1.000000000000001E7;
+ java.math.BigDecimal bd = new java.math.BigDecimal(d);
+ StringBuffer sb = new StringBuffer("");
+ FieldPosition fp = new FieldPosition(0);
+ logln("d = " + d);
+ logln("BigDecimal.toString(): " + bd.toString());
+ df.format(d, sb, fp);
+ if (!sb.toString().equals("10000000.0000000100")) {
+ errln("DecimalFormat.format(): " + sb.toString());
+ }
+ }
+
+ /**
+ * DecimalFormat.format() loses precision
+ */
+ public void Test4090504 ()
+ {
+ double d = 1;
+ logln("d = " + d);
+ DecimalFormat df = new DecimalFormat();
+ StringBuffer sb;
+ FieldPosition fp;
+ try {
+ for (int i = 17; i <= 20; i++) {
+ df.setMaximumFractionDigits(i);
+ sb = new StringBuffer("");
+ fp = new FieldPosition(0);
+ logln(" getMaximumFractionDigits() = " + i);
+ logln(" formated: " + df.format(d, sb, fp));
+ }
+ } catch (Exception foo) {
+ errln("Bug 4090504 regression test failed. Message : " + foo.getMessage());
+ }
+ }
+ /**
+ * DecimalFormat.parse(String str, ParsePosition pp) loses precision
+ */
+ public void Test4095713 ()
+ {
+ DecimalFormat df = new DecimalFormat();
+ String str = "0.1234";
+ Double d1 = new Double(str);
+ Number d2 = df.parse(str, new ParsePosition(0));
+ logln(d1.toString());
+ if (d2.doubleValue() != d1.doubleValue())
+ errln("Bug 4095713 test failed, new double value : " + d2.doubleValue());
+ }
+
+ /**
+ * DecimalFormat.parse() fails when multiplier is not set to 1
+ */
+ public void Test4092561 ()
+ {
+ Locale savedLocale = Locale.getDefault();
+ Locale.setDefault(Locale.US);
+ DecimalFormat df = new DecimalFormat();
+ String str = Long.toString(Long.MIN_VALUE);
+ logln("Long.MIN_VALUE : " + df.parse(str, new ParsePosition(0)).toString());
+ df.setMultiplier(100);
+ Number num = df.parse(str, new ParsePosition(0));
+ if (num.doubleValue() != -9.223372036854776E16) {
+ errln("Bug 4092561 test failed when multiplier is set to not 1.");
+ }
+ Locale.setDefault(savedLocale);
+ }
+
+ /**
+ * DecimalFormat: Negative format ignored.
+ */
+ public void Test4092480 ()
+ {
+ DecimalFormat dfFoo = new DecimalFormat("000");
+
+ try {
+ dfFoo.applyPattern("0000;-000");
+ if (!dfFoo.toPattern().equals("#0000"))
+ errln("dfFoo.toPattern : " + dfFoo.toPattern());
+ logln(dfFoo.format(42));
+ logln(dfFoo.format(-42));
+ dfFoo.applyPattern("000;-000");
+ if (!dfFoo.toPattern().equals("#000"))
+ errln("dfFoo.toPattern : " + dfFoo.toPattern());
+ logln(dfFoo.format(42));
+ logln(dfFoo.format(-42));
+
+ dfFoo.applyPattern("000;-0000");
+ if (!dfFoo.toPattern().equals("#000"))
+ errln("dfFoo.toPattern : " + dfFoo.toPattern());
+ logln(dfFoo.format(42));
+ logln(dfFoo.format(-42));
+
+ dfFoo.applyPattern("0000;-000");
+ if (!dfFoo.toPattern().equals("#0000"))
+ errln("dfFoo.toPattern : " + dfFoo.toPattern());
+ logln(dfFoo.format(42));
+ logln(dfFoo.format(-42));
+ } catch (Exception foo) {
+ errln("Message " + foo.getMessage());
+ }
+ }
+ /**
+ * NumberFormat.getCurrencyInstance() produces format that uses
+ * decimal separator instead of monetary decimal separator.
+ *
+ * Rewrote this test not to depend on the actual pattern. Pattern should
+ * never contain the monetary separator! Decimal separator in pattern is
+ * interpreted as monetary separator if currency symbol is seen!
+ */
+ public void Test4087244 () {
+ Locale de = new Locale("pt", "PT");
+ DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance(de);
+ DecimalFormatSymbols sym = df.getDecimalFormatSymbols();
+ sym.setMonetaryDecimalSeparator('$');
+ df.setDecimalFormatSymbols(sym);
+ char decSep = sym.getDecimalSeparator();
+ char monSep = sym.getMonetaryDecimalSeparator();
+ //char zero = sym.getZeroDigit(); //The variable is never used
+ if (decSep == monSep) {
+ errln("ERROR in test: want decimal sep != monetary sep");
+ } else {
+ df.setMinimumIntegerDigits(1);
+ df.setMinimumFractionDigits(2);
+ String str = df.format(1.23);
+ String monStr = "1" + monSep + "23";
+ String decStr = "1" + decSep + "23";
+ if (str.indexOf(monStr) >= 0 && str.indexOf(decStr) < 0) {
+ logln("OK: 1.23 -> \"" + str + "\" contains \"" +
+ monStr + "\" and not \"" + decStr + '"');
+ } else {
+ errln("FAIL: 1.23 -> \"" + str + "\", should contain \"" +
+ monStr +
+ "\" and not \"" + decStr + '"');
+ }
+ }
+ }
+ /**
+ * Number format data rounding errors for locale FR
+ */
+ public void Test4070798 () {
+ NumberFormat formatter;
+ String tempString;
+ /* User error :
+ String expectedDefault = "-5\u00a0789,987";
+ String expectedCurrency = "5\u00a0789,98\u00a0F";
+ String expectedPercent = "-578\u00a0998%";
+ */
+ String expectedDefault = "-5\u00a0789,988";
+ String expectedCurrency = "5\u00a0789,99\u00a0" + EURO; // euro
+ String expectedPercent = "-578\u00a0999\u00a0%";
+
+ formatter = NumberFormat.getNumberInstance(Locale.FRANCE);
+ tempString = formatter.format (-5789.9876);
+
+ if (tempString.equals(expectedDefault)) {
+ logln ("Bug 4070798 default test passed.");
+ } else {
+ errln("Failed:" +
+ " Expected " + expectedDefault +
+ " Received " + tempString );
+ }
+
+
+ formatter = NumberFormat.getCurrencyInstance(Locale.FRANCE);
+ tempString = formatter.format( 5789.9876 );
+
+ if (tempString.equals(expectedCurrency) ) {
+ logln ("Bug 4070798 currency test assed.");
+ } else {
+ errln("Failed:" +
+ " Expected " + expectedCurrency +
+ " Received " + tempString );
+ }
+
+
+ formatter = NumberFormat.getPercentInstance(Locale.FRANCE);
+ tempString = formatter.format (-5789.9876);
+
+ if (tempString.equals(expectedPercent) ) {
+ logln ("Bug 4070798 percentage test passed.");
+ } else {
+ errln("Failed:" +
+ " Expected " + expectedPercent +
+ " Received " + tempString );
+ }
+ }
+ /**
+ * Data rounding errors for French (Canada) locale
+ */
+ public void Test4071005 () {
+
+ NumberFormat formatter;
+ String tempString;
+ /* user error :
+ String expectedDefault = "-5 789,987";
+ String expectedCurrency = "5 789,98\u00a0$";
+ String expectedPercent = "-578 998%";
+ */
+ String expectedDefault = "-5\u00a0789,988";
+ String expectedCurrency = "5\u00a0789,99\u00a0$";
+ String expectedPercent = "-578\u00a0999\u00A0%";
+
+ formatter = NumberFormat.getNumberInstance(Locale.CANADA_FRENCH);
+ tempString = formatter.format (-5789.9876);
+ if (tempString.equals(expectedDefault)) {
+ logln ("Bug 4071005 default test passed.");
+ } else {
+ errln("Failed:" +
+ " Expected " + expectedDefault +
+ " Received " + tempString );
+ }
+
+ formatter = NumberFormat.getCurrencyInstance(Locale.CANADA_FRENCH);
+ tempString = formatter.format( 5789.9876 ) ;
+
+ if (tempString.equals(expectedCurrency) ) {
+ logln ("Bug 4071005 currency test passed.");
+ } else {
+ errln("Failed:" +
+ " Expected " + expectedCurrency +
+ " Received " + tempString );
+ }
+ formatter = NumberFormat.getPercentInstance(Locale.CANADA_FRENCH);
+ tempString = formatter.format (-5789.9876);
+
+ if (tempString.equals(expectedPercent) ) {
+ logln ("Bug 4071005 percentage test passed.");
+ } else {
+ errln("Failed:" +
+ " Expected " + expectedPercent +
+ " Received " + tempString );
+ }
+ }
+
+ /**
+ * Data rounding errors for German (Germany) locale
+ */
+ public void Test4071014 () {
+ NumberFormat formatter;
+ String tempString;
+ /* user error :
+ String expectedDefault = "-5.789,987";
+ String expectedCurrency = "5.789,98\u00a0DM";
+ String expectedPercent = "-578.998%";
+ */
+ String expectedDefault = "-5.789,988";
+ String expectedCurrency = "5.789,99\u00a0" + EURO;
+ String expectedPercent = "-578.999\u00a0%";
+
+ formatter = NumberFormat.getNumberInstance(Locale.GERMANY);
+ tempString = formatter.format (-5789.9876);
+
+ if (tempString.equals(expectedDefault)) {
+ logln ("Bug 4071014 default test passed.");
+ } else {
+ errln("Failed:" +
+ " Expected " + expectedDefault +
+ " Received " + tempString );
+ }
+
+ formatter = NumberFormat.getCurrencyInstance(Locale.GERMANY);
+ tempString = formatter.format( 5789.9876 ) ;
+
+ if (tempString.equals(expectedCurrency) ) {
+ logln ("Bug 4071014 currency test passed.");
+ } else {
+ errln("Failed:" +
+ " Expected " + expectedCurrency +
+ " Received " + tempString );
+ }
+
+ formatter = NumberFormat.getPercentInstance(Locale.GERMANY);
+ tempString = formatter.format (-5789.9876);
+
+ if (tempString.equals(expectedPercent) ) {
+ logln ("Bug 4071014 percentage test passed.");
+ } else {
+ errln("Failed:" +
+ " Expected " + expectedPercent +
+ " Received " + tempString );
+ }
+
+ }
+ /**
+ * Data rounding errors for Italian locale number formats
+ * Note- with the Euro, there is no need for currency rounding anymore
+ */
+ public void Test4071859 () {
+ NumberFormat formatter;
+ String tempString;
+ /* user error :
+ String expectedDefault = "-5.789,987";
+ String expectedCurrency = "-L.\u00a05.789,98";
+ String expectedPercent = "-578.998%";
+ */
+ String expectedDefault = "-5.789,988";
+ String expectedCurrency = "-" + EURO + "\u00a05.789,99";
+ String expectedPercent = "-578.999%";
+
+ formatter = NumberFormat.getNumberInstance(Locale.ITALY);
+ tempString = formatter.format (-5789.9876);
+
+ if (tempString.equals(expectedDefault)) {
+ logln ("Bug 4071859 default test passed.");
+ } else {
+ errln("a) Failed:" +
+ " Expected " + expectedDefault +
+ " Received " + tempString );
+ }
+
+ formatter = NumberFormat.getCurrencyInstance(Locale.ITALY);
+ tempString = formatter.format( -5789.9876 ) ;
+
+ if (tempString.equals(expectedCurrency) ) {
+ logln ("Bug 4071859 currency test passed.");
+ } else {
+ errln("b) Failed:" +
+ " Expected " + expectedCurrency +
+ " Received " + tempString );
+ }
+
+ formatter = NumberFormat.getPercentInstance(Locale.ITALY);
+ tempString = formatter.format (-5789.9876);
+
+ if (tempString.equals(expectedPercent) ) {
+ logln ("Bug 4071859 percentage test passed.");
+ } else {
+ errln("c) Failed:" +
+ " Expected " + expectedPercent +
+ " Received " + tempString );
+ }
+
+ }
+ /* bug 4071859
+ * Test rounding for nearest even.
+ */
+ public void Test4093610()
+ {
+ DecimalFormat df = new DecimalFormat("#0.#");
+ roundingTest(df, 12.35, "12.4");
+ roundingTest(df, 12.45, "12.4");
+ roundingTest(df, 12.452,"12.5");
+ roundingTest(df, 12.55, "12.6");
+ roundingTest(df, 12.65, "12.6");
+ roundingTest(df, 12.652,"12.7");
+ roundingTest(df, 12.75, "12.8");
+ roundingTest(df, 12.752,"12.8");
+ roundingTest(df, 12.85, "12.8");
+ roundingTest(df, 12.852,"12.9");
+ roundingTest(df, 12.95, "13");
+ roundingTest(df, 12.952,"13");
+
+ }
+ void roundingTest(DecimalFormat df, double x, String expected)
+ {
+ String out = df.format(x);
+ logln("" + x + " formats with 1 fractional digits to " + out);
+ if (!out.equals(expected)) errln("FAIL: Expected " + expected);
+ }
+ /**
+ * Tests the setMaximumFractionDigits limit.
+ */
+ public void Test4098741()
+ {
+ try {
+ NumberFormat fmt = NumberFormat.getPercentInstance();
+ fmt.setMaximumFractionDigits(20);
+ logln(fmt.format(.001));
+ } catch (Exception foo) {
+ warnln("Bug 4098471 failed with exception thrown : " + foo.getMessage());
+ }
+ }
+ /**
+ * Tests illegal pattern exception.
+ * Fix comment : HShih A31 Part1 will not be fixed and javadoc needs to be updated.
+ * Part2 has been fixed.
+ */
+ public void Test4074454()
+ {
+ try {
+ DecimalFormat fmt = new DecimalFormat("#,#00.00;-#.#");
+ logln("format 3456.78: " + fmt.format(3456.78)); //fix "The variable 'fmt' is never used"
+ logln("Inconsistent negative pattern is fine.");
+ DecimalFormat newFmt = new DecimalFormat("#,#00.00 p''ieces;-#,#00.00 p''ieces");
+ String tempString = newFmt.format(3456.78);
+ if (!tempString.equals("3,456.78 p'ieces"))
+ errln("Failed! 3456.78 p'ieces expected, but got : " + tempString);
+ } catch (Exception foo) {
+ warnln("An exception was thrown for any inconsistent negative pattern.");
+ }
+ }
+ /**
+ * Tests all different comments.
+ * Response to some comments :
+ * [1] DecimalFormat.parse API documentation is more than just one line.
+ * This is not a reproducable doc error in 116 source code.
+ * [2] See updated javadoc.
+ * [3] Fixed.
+ * [4] NumberFormat.parse(String, ParsePosition) : If parsing fails,
+ * a null object will be returned. The unchanged parse position also
+ * reflects an error.
+ * NumberFormat.parse(String) : If parsing fails, an ParseException
+ * will be thrown.
+ * See updated javadoc for more details.
+ * [5] See updated javadoc.
+ * [6] See updated javadoc.
+ * [7] This is a correct behavior if the DateFormat object is linient.
+ * Otherwise, an IllegalArgumentException will be thrown when formatting
+ * "January 35". See GregorianCalendar class javadoc for more details.
+ */
+ public void Test4099404()
+ {
+ try {
+ DecimalFormat fmt = new DecimalFormat("000.0#0");
+ logln("format 3456.78: " + fmt.format(3456.78)); //fix "The variable 'fmt' is never used"
+ errln("Bug 4099404 failed applying illegal pattern \"000.0#0\"");
+ } catch (Exception foo) {
+ logln("Bug 4099404 pattern \"000.0#0\" passed");
+ }
+ try {
+ DecimalFormat fmt = new DecimalFormat("0#0.000");
+ logln("format 3456.78: " + fmt.format(3456.78)); //fix "The variable 'fmt' is never used"
+ errln("Bug 4099404 failed applying illegal pattern \"0#0.000\"");
+ } catch (Exception foo) {
+ logln("Bug 4099404 pattern \"0#0.000\" passed");
+ }
+ }
+ /**
+ * DecimalFormat.applyPattern doesn't set minimum integer digits
+ */
+ public void Test4101481()
+ {
+ DecimalFormat sdf = new DecimalFormat("#,##0");
+ if (sdf.getMinimumIntegerDigits() != 1)
+ errln("Minimum integer digits : " + sdf.getMinimumIntegerDigits());
+ }
+ /**
+ * Tests ParsePosition.setErrorPosition() and ParsePosition.getErrorPosition().
+ */
+ public void Test4052223()
+ {
+ try {
+ DecimalFormat fmt = new DecimalFormat("#,#00.00");
+ Number num = fmt.parse("abc3");
+ errln("Bug 4052223 failed : can't parse string \"a\". Got " + num);
+ } catch (ParseException foo) {
+ logln("Caught expected ParseException : " + foo.getMessage() + " at index : " + foo.getErrorOffset());
+ }
+ }
+ /**
+ * API tests for API addition request A9.
+ */
+ public void Test4061302()
+ {
+ DecimalFormatSymbols fmt = new DecimalFormatSymbols();
+ String currency = fmt.getCurrencySymbol();
+ String intlCurrency = fmt.getInternationalCurrencySymbol();
+ char monDecSeparator = fmt.getMonetaryDecimalSeparator();
+ if (currency.equals("") ||
+ intlCurrency.equals("") ||
+ monDecSeparator == 0) {
+ errln("getCurrencySymbols failed, got empty string.");
+ }
+ logln("Before set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator);
+ fmt.setCurrencySymbol("XYZ");
+ fmt.setInternationalCurrencySymbol("ABC");
+ fmt.setMonetaryDecimalSeparator('*');
+ currency = fmt.getCurrencySymbol();
+ intlCurrency = fmt.getInternationalCurrencySymbol();
+ monDecSeparator = fmt.getMonetaryDecimalSeparator();
+ if (!currency.equals("XYZ") ||
+ !intlCurrency.equals("ABC") ||
+ monDecSeparator != '*') {
+ errln("setCurrencySymbols failed.");
+ }
+ logln("After set ==> Currency : " + currency + " Intl Currency : " + intlCurrency + " Monetary Decimal Separator : " + monDecSeparator);
+ }
+ /**
+ * API tests for API addition request A23. FieldPosition.getBeginIndex and
+ * FieldPosition.getEndIndex.
+ */
+ public void Test4062486()
+ {
+ DecimalFormat fmt = new DecimalFormat("#,##0.00");
+ StringBuffer formatted = new StringBuffer();
+ FieldPosition field = new FieldPosition(0);
+ Double num = new Double(1234.5);
+ fmt.format(num, formatted, field);
+ if (field.getBeginIndex() != 0 && field.getEndIndex() != 5)
+ errln("Format 1234.5 failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex());
+ field.setBeginIndex(7);
+ field.setEndIndex(4);
+ if (field.getBeginIndex() != 7 && field.getEndIndex() != 4)
+ errln("Set begin/end field indexes failed. Begin index: " + field.getBeginIndex() + " End index: " + field.getEndIndex());
+ }
+
+ /**
+ * DecimalFormat.parse incorrectly works with a group separator.
+ */
+ public void Test4108738()
+ {
+
+ DecimalFormat df = new DecimalFormat("#,##0.###", new
+ DecimalFormatSymbols(java.util.Locale.US));
+ String text = "1.222,111";
+ Number num = df.parse(text,new ParsePosition(0));
+ if (!num.toString().equals("1.222"))
+ errln("\"" + text + "\" is parsed as " + num);
+ text = "1.222x111";
+ num = df.parse(text,new ParsePosition(0));
+ if (!num.toString().equals("1.222"))
+ errln("\"" + text + "\" is parsed as " + num);
+ }
+
+ /**
+ * DecimalFormat.format() incorrectly formats negative doubles.
+ */
+ public void Test4106658()
+ {
+ Locale savedLocale = Locale.getDefault();
+ Locale.setDefault(Locale.US);
+ DecimalFormat df = new DecimalFormat(); // Corrected; see 4147706
+ double d1 = -0.0;
+ double d2 = -0.0001;
+ StringBuffer buffer = new StringBuffer();
+ logln("pattern: \"" + df.toPattern() + "\"");
+ df.format(d1, buffer, new FieldPosition(0));
+ if (!buffer.toString().equals("-0")) { // Corrected; see 4147706
+ errln(d1 + " is formatted as " + buffer);
+ }
+ buffer.setLength(0);
+ df.format(d2, buffer, new FieldPosition(0));
+ if (!buffer.toString().equals("-0")) { // Corrected; see 4147706
+ errln(d2 + " is formatted as " + buffer);
+ }
+ Locale.setDefault(savedLocale);
+ }
+
+ /**
+ * DecimalFormat.parse returns 0 if string parameter is incorrect.
+ */
+ public void Test4106662()
+ {
+ DecimalFormat df = new DecimalFormat();
+ String text = "x";
+ ParsePosition pos1 = new ParsePosition(0), pos2 = new ParsePosition(0);
+
+ logln("pattern: \"" + df.toPattern() + "\"");
+ Number num = df.parse(text, pos1);
+ if (num != null) {
+ errln("Test Failed: \"" + text + "\" is parsed as " + num);
+ }
+ df = null;
+ df = new DecimalFormat("$###.00");
+ num = df.parse("$", pos2);
+ if (num != null){
+ errln("Test Failed: \"$\" is parsed as " + num);
+ }
+ }
+
+ /**
+ * NumberFormat.parse doesn't return null
+ */
+ public void Test4114639()
+ {
+ NumberFormat format = NumberFormat.getInstance();
+ String text = "time 10:x";
+ ParsePosition pos = new ParsePosition(8);
+ Number result = format.parse(text, pos);
+ if (result != null) errln("Should return null but got : " + result); // Should be null; it isn't
+ }
+
+ /**
+ * DecimalFormat.format(long n) fails if n * multiplier > MAX_LONG.
+ */
+ public void Test4106664()
+ {
+ DecimalFormat df = new DecimalFormat();
+ long n = 1234567890123456L;
+ int m = 12345678;
+ BigInteger bigN = BigInteger.valueOf(n);
+ bigN = bigN.multiply(BigInteger.valueOf(m));
+ df.setMultiplier(m);
+ df.setGroupingUsed(false);
+ logln("formated: " +
+ df.format(n, new StringBuffer(), new FieldPosition(0)));
+ logln("expected: " + bigN.toString());
+ }
+ /**
+ * DecimalFormat.format incorrectly formats -0.0.
+ */
+ public void Test4106667()
+ {
+ Locale savedLocale = Locale.getDefault();
+ Locale.setDefault(Locale.US);
+ DecimalFormat df = new DecimalFormat();
+ df.setPositivePrefix("+");
+ double d = -0.0;
+ logln("pattern: \"" + df.toPattern() + "\"");
+ StringBuffer buffer = new StringBuffer();
+ df.format(d, buffer, new FieldPosition(0));
+ if (!buffer.toString().equals("-0")) { // Corrected; see 4147706
+ errln(d + " is formatted as " + buffer);
+ }
+ Locale.setDefault(savedLocale);
+ }
+
+ /**
+ * DecimalFormat.setMaximumIntegerDigits() works incorrectly.
+ */
+ public void Test4110936()
+ {
+ NumberFormat nf = NumberFormat.getInstance();
+ nf.setMaximumIntegerDigits(128);
+ logln("setMaximumIntegerDigits(128)");
+ if (nf.getMaximumIntegerDigits() != 128)
+ errln("getMaximumIntegerDigits() returns " +
+ nf.getMaximumIntegerDigits());
+ }
+
+ /**
+ * Locale data should use generic currency symbol
+ *
+ * 1) Make sure that all currency formats use the generic currency symbol.
+ * 2) Make sure we get the same results using the generic symbol or a
+ * hard-coded one.
+ */
+ public void Test4122840()
+ {
+ Locale[] locales = NumberFormat.getAvailableLocales();
+
+ for (int i = 0; i < locales.length; i++) {
+ UResourceBundle rb = UResourceBundle.getBundleInstance(ICUResourceBundle.ICU_BASE_NAME,locales[i]);
+
+ //
+ // Get the currency pattern for this locale. We have to fish it
+ // out of the ResourceBundle directly, since DecimalFormat.toPattern
+ // will return the localized symbol, not \00a4
+ //
+ UResourceBundle numPatterns = rb.get("NumberPatterns");
+ String pattern = numPatterns.getString(1);
+
+ if (pattern.indexOf('\u00A4') == -1 ) { // 'x' not "x" -- workaround bug in IBM JDK 1.4.1
+ errln("Currency format for " + locales[i] +
+ " does not contain generic currency symbol:" +
+ pattern );
+ }
+
+ // Create a DecimalFormat using the pattern we got and format a number
+ DecimalFormatSymbols symbols = new DecimalFormatSymbols(locales[i]);
+ DecimalFormat fmt1 = new DecimalFormat(pattern, symbols);
+
+ String result1 = fmt1.format(1.111);
+
+ //
+ // Now substitute in the locale's currency symbol and create another
+ // pattern. Replace the decimal separator with the monetary separator.
+ //
+ //char decSep = symbols.getDecimalSeparator(); //The variable is never used
+ char monSep = symbols.getMonetaryDecimalSeparator();
+ StringBuffer buf = new StringBuffer(pattern);
+ for (int j = 0; j < buf.length(); j++) {
+ if (buf.charAt(j) == '\u00a4') {
+ String cur = "'" + symbols.getCurrencySymbol() + "'";
+ buf.replace(j, j+1, cur);
+ j += cur.length() - 1;
+ }
+ }
+ symbols.setDecimalSeparator(monSep);
+ DecimalFormat fmt2 = new DecimalFormat(buf.toString(), symbols);
+
+ String result2 = fmt2.format(1.111);
+
+ // NOTE: en_IN is a special case (ChoiceFormat currency display name)
+ if (!result1.equals(result2) &&
+ !locales[i].toString().equals("en_IN")) {
+ errln("Results for " + locales[i] + " differ: " +
+ result1 + " vs " + result2);
+ }
+ }
+ }
+
+ /**
+ * DecimalFormat.format() delivers wrong string.
+ */
+ public void Test4125885()
+ {
+ double rate = 12.34;
+ DecimalFormat formatDec = new DecimalFormat ("000.00");
+ logln("toPattern: " + formatDec.toPattern());
+ String rateString= formatDec.format(rate);
+ if (!rateString.equals("012.34"))
+ errln("result : " + rateString + " expected : 012.34");
+ rate = 0.1234;
+ formatDec = null;
+ formatDec = new DecimalFormat ("+000.00%;-000.00%");
+ logln("toPattern: " + formatDec.toPattern());
+ rateString= formatDec.format(rate);
+ if (!rateString.equals("+012.34%"))
+ errln("result : " + rateString + " expected : +012.34%");
+ }
+
+ /**
+ **
+ * DecimalFormat produces extra zeros when formatting numbers.
+ */
+ public void Test4134034() {
+ DecimalFormat nf = new DecimalFormat("##,###,###.00");
+
+ String f = nf.format(9.02);
+ if (f.equals("9.02")) logln(f + " ok"); else errln("9.02 -> " + f + "; want 9.02");
+
+ f = nf.format(0);
+ if (f.equals(".00")) logln(f + " ok"); else errln("0 -> " + f + "; want .00");
+ }
+
+ /**
+ * CANNOT REPRODUCE - This bug could not be reproduced. It may be
+ * a duplicate of 4134034.
+ *
+ * JDK 1.1.6 Bug, did NOT occur in 1.1.5
+ * Possibly related to bug 4125885.
+ *
+ * This class demonstrates a regression in version 1.1.6
+ * of DecimalFormat class.
+ *
+ * 1.1.6 Results
+ * Value 1.2 Format #.00 Result '01.20' !!!wrong
+ * Value 1.2 Format 0.00 Result '001.20' !!!wrong
+ * Value 1.2 Format 00.00 Result '0001.20' !!!wrong
+ * Value 1.2 Format #0.0# Result '1.2'
+ * Value 1.2 Format #0.00 Result '001.20' !!!wrong
+ *
+ * 1.1.5 Results
+ * Value 1.2 Format #.00 Result '1.20'
+ * Value 1.2 Format 0.00 Result '1.20'
+ * Value 1.2 Format 00.00 Result '01.20'
+ * Value 1.2 Format #0.0# Result '1.2'
+ * Value 1.2 Format #0.00 Result '1.20'
+ */
+ public void Test4134300() {
+ String[] DATA = {
+ // Pattern Expected string
+ "#.00", "1.20",
+ "0.00", "1.20",
+ "00.00", "01.20",
+ "#0.0#", "1.2",
+ "#0.00", "1.20",
+ };
+ for (int i=0; i<DATA.length; i+=2) {
+ String result = new DecimalFormat(DATA[i]).format(1.2);
+ if (!result.equals(DATA[i+1])) {
+ errln("Fail: 1.2 x " + DATA[i] + " = " + result +
+ "; want " + DATA[i+1]);
+ }
+ else {
+ logln("Ok: 1.2 x " + DATA[i] + " = " + result);
+ }
+ }
+ }
+
+ /**
+ * Empty pattern produces double negative prefix.
+ */
+ public void Test4140009() {
+ final double IN[] = { 123.456, -123.456 };
+ final String OUT[] = { "123.456", "-123.456" };
+ for (int i=0; i<2; ++i) {
+ DecimalFormat f = null;
+ switch (i) {
+ case 0:
+ f = new DecimalFormat("",
+ new DecimalFormatSymbols(Locale.ENGLISH));
+ break;
+ case 1:
+ f = new DecimalFormat("#.#",
+ new DecimalFormatSymbols(Locale.ENGLISH));
+ f.applyPattern("");
+ break;
+ }
+ for (int j=0; j<2; ++j) {
+ assertEquals("<empty pat " + i + ">.format(" + IN[j] + ")",
+ OUT[j], f.format(IN[j]));
+ }
+ }
+ }
+
+//#if defined(FOUNDATION10)
+//#else
+ /**
+ * BigDecimal numbers get their fractions truncated by NumberFormat.
+ */
+ public void Test4141750() {
+ try {
+ String str = "12345.67";
+ java.math.BigDecimal bd = new java.math.BigDecimal(str);
+ String sd = NumberFormat.getInstance(Locale.US).format(bd);
+ if (!sd.endsWith("67")) errln("Fail: " + str + " x format -> " + sd);
+ }
+ catch (Exception e) {
+ warnln(e.toString());
+ //e.printStackTrace();
+ }
+ }
+//#endif
+
+ /**
+ * DecimalFormat toPattern() doesn't quote special characters or handle
+ * single quotes.
+ */
+ public void Test4145457() {
+ try {
+ DecimalFormat nf = (DecimalFormat)NumberFormat.getInstance();
+ DecimalFormatSymbols sym = nf.getDecimalFormatSymbols();
+ sym.setDecimalSeparator('\'');
+ nf.setDecimalFormatSymbols(sym);
+ double pi = 3.14159;
+
+ String[] PATS = { "#.00 'num''ber'", "''#.00''" };
+
+ for (int i=0; i<PATS.length; ++i) {
+ nf.applyPattern(PATS[i]);
+ String out = nf.format(pi);
+ String pat = nf.toPattern();
+ double val = nf.parse(out).doubleValue();
+
+ nf.applyPattern(pat);
+ String out2 = nf.format(pi);
+ String pat2 = nf.toPattern();
+ double val2 = nf.parse(out2).doubleValue();
+
+ if (!pat.equals(pat2))
+ errln("Fail with \"" + PATS[i] + "\": Patterns should concur, \"" +
+ pat + "\" vs. \"" + pat2 + "\"");
+ else
+ logln("Ok \"" + PATS[i] + "\" toPattern() -> \"" + pat + '"');
+
+ if (val == val2 && out.equals(out2)) {
+ logln("Ok " + pi + " x \"" + PATS[i] + "\" -> \"" +
+ out + "\" -> " + val + " -> \"" +
+ out2 + "\" -> " + val2);
+ }
+ else {
+ errln("Fail " + pi + " x \"" + PATS[i] + "\" -> \"" +
+ out + "\" -> " + val + " -> \"" +
+ out2 + "\" -> " + val2);
+ }
+ }
+ }
+ catch (ParseException e) {
+ errln("Fail: " + e);
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * DecimalFormat.applyPattern() sets minimum integer digits incorrectly.
+ * CANNOT REPRODUCE
+ * This bug is a duplicate of 4139344, which is a duplicate of 4134300
+ */
+ public void Test4147295() {
+ DecimalFormat sdf = new DecimalFormat();
+ String pattern = "#,###";
+ logln("Applying pattern \"" + pattern + "\"");
+ sdf.applyPattern(pattern);
+ int minIntDig = sdf.getMinimumIntegerDigits();
+ if (minIntDig != 0) {
+ errln("Test failed");
+ errln(" Minimum integer digits : " + minIntDig);
+ errln(" new pattern: " + sdf.toPattern());
+ } else {
+ logln("Test passed");
+ logln(" Minimum integer digits : " + minIntDig);
+ }
+ }
+
+ /**
+ * DecimalFormat formats -0.0 as +0.0
+ * See also older related bug 4106658, 4106667
+ */
+ public void Test4147706() {
+ DecimalFormat df = new DecimalFormat("#,##0.0##");
+ df.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.ENGLISH));
+ double d1 = -0.0;
+ double d2 = -0.0001;
+ StringBuffer f1 = df.format(d1, new StringBuffer(), new FieldPosition(0));
+ StringBuffer f2 = df.format(d2, new StringBuffer(), new FieldPosition(0));
+ if (!f1.toString().equals("-0.0")) {
+ errln(d1 + " x \"" + df.toPattern() + "\" is formatted as \"" + f1 + '"');
+ }
+ if (!f2.toString().equals("-0.0")) {
+ errln(d2 + " x \"" + df.toPattern() + "\" is formatted as \"" + f2 + '"');
+ }
+ }
+
+ /**
+ * NumberFormat cannot format Double.MAX_VALUE
+ */
+ public void Test4162198() {
+ double dbl = Double.MAX_VALUE;
+ NumberFormat f = NumberFormat.getInstance();
+ f.setMaximumFractionDigits(Integer.MAX_VALUE);
+ f.setMaximumIntegerDigits(Integer.MAX_VALUE);
+ String s = f.format(dbl);
+ logln("The number " + dbl + " formatted to " + s);
+ Number n = null;
+ try {
+ n = f.parse(s);
+ } catch (java.text.ParseException e) {
+ errln("Caught a ParseException:");
+ e.printStackTrace();
+ }
+ logln("The string " + s + " parsed as " + n);
+ if (n.doubleValue() != dbl) {
+ errln("Round trip failure");
+ }
+ }
+
+ /**
+ * NumberFormat does not parse negative zero.
+ */
+ public void Test4162852() throws ParseException {
+ for (int i=0; i<2; ++i) {
+ NumberFormat f = (i == 0) ? NumberFormat.getInstance()
+ : NumberFormat.getPercentInstance();
+ double d = -0.0;
+ String s = f.format(d);
+ double e = f.parse(s).doubleValue();
+ logln("" +
+ d + " -> " +
+ '"' + s + '"' + " -> " +
+ e);
+ if (e != 0.0 || 1.0/e > 0.0) {
+ logln("Failed to parse negative zero");
+ }
+ }
+ }
+
+ /**
+ * NumberFormat truncates data
+ */
+ public void Test4167494() throws Exception {
+ NumberFormat fmt = NumberFormat.getInstance(Locale.US);
+
+ double a = Double.MAX_VALUE;
+ String s = fmt.format(a);
+ double b = fmt.parse(s).doubleValue();
+ boolean match = a == b;
+ if (match) {
+ logln("" + a + " -> \"" + s + "\" -> " + b + " ok");
+ } else {
+ errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL");
+ }
+
+ // We don't test Double.MIN_VALUE because the locale data for the US
+ // currently doesn't specify enough digits to display Double.MIN_VALUE.
+ // This is correct for now; however, we leave this here as a reminder
+ // in case we want to address this later.
+ if (false) {
+ a = Double.MIN_VALUE;
+ s = fmt.format(a);
+ b = fmt.parse(s).doubleValue();
+ match = a == b;
+ if (match) {
+ logln("" + a + " -> \"" + s + "\" -> " + b + " ok");
+ } else {
+ errln("" + a + " -> \"" + s + "\" -> " + b + " FAIL");
+ }
+ }
+ }
+
+ /**
+ * DecimalFormat.parse() fails when ParseIntegerOnly set to true
+ */
+ public void Test4170798() {
+ Locale savedLocale = Locale.getDefault();
+ Locale.setDefault(Locale.US);
+ DecimalFormat df = new DecimalFormat();
+ df.setParseIntegerOnly(true);
+ Number n = df.parse("-0.0", new ParsePosition(0));
+ if (!(n instanceof Double)
+ || n.intValue() != 0) {
+ errln("FAIL: parse(\"-0.0\") returns " +
+ n + " (" + n.getClass().getName() + ')');
+ }
+ Locale.setDefault(savedLocale);
+ }
+
+ /**
+ * toPattern only puts the first grouping separator in.
+ */
+ public void Test4176114() {
+ String[] DATA = {
+ "00", "#00",
+ "000", "#000", // No grouping
+ "#000", "#000", // No grouping
+ "#,##0", "#,##0",
+ "#,000", "#,000",
+ "0,000", "#0,000",
+ "00,000", "#00,000",
+ "000,000", "#,000,000",
+ "0,000,000,000,000.0000", "#0,000,000,000,000.0000", // Reported
+ };
+ for (int i=0; i<DATA.length; i+=2) {
+ DecimalFormat df = new DecimalFormat(DATA[i]);
+ String s = df.toPattern();
+ if (!s.equals(DATA[i+1])) {
+ errln("FAIL: " + DATA[i] + " -> " + s + ", want " + DATA[i+1]);
+ }
+ }
+ }
+
+ /**
+ * DecimalFormat is incorrectly rounding numbers like 1.2501 to 1.2
+ */
+ public void Test4179818() {
+ String DATA[] = {
+ // Input Pattern Expected output
+ "1.2511", "#.#", "1.3",
+ "1.2501", "#.#", "1.3",
+ "0.9999", "#", "1",
+ };
+ DecimalFormat fmt = new DecimalFormat("#",
+ new DecimalFormatSymbols(Locale.US));
+ for (int i=0; i<DATA.length; i+=3) {
+ double in = Double.valueOf(DATA[i]).doubleValue();
+ String pat = DATA[i+1];
+ String exp = DATA[i+2];
+ fmt.applyPattern(pat);
+ String out = fmt.format(in);
+ if (out.equals(exp)) {
+ logln("Ok: " + in + " x " + pat + " = " + out);
+ } else {
+ errln("FAIL: " + in + " x " + pat + " = " + out +
+ ", expected " + exp);
+ }
+ }
+ }
+
+ public void Test4185761() throws IOException, ClassNotFoundException {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+
+ NumberFormat nf = NumberFormat.getInstance(Locale.US);
+
+ // Set special values we are going to search for in the output byte stream
+ // These are all legal values.
+ nf.setMinimumIntegerDigits(0x111); // Keep under 309
+ nf.setMaximumIntegerDigits(0x112); // Keep under 309
+ nf.setMinimumFractionDigits(0x113); // Keep under 340
+ nf.setMaximumFractionDigits(0x114); // Keep under 340
+
+ oos.writeObject(nf);
+ oos.flush();
+ baos.close();
+
+ byte[] bytes = baos.toByteArray();
+
+ // Scan for locations of min/max int/fract values in the byte array.
+ // At the moment (ICU4J 2.1), there is only one instance of each target pair
+ // in the byte stream, so assume first match is it. Note this is not entirely
+ // failsafe, and needs to be checked if we change the package or structure of
+ // this class.
+ // Current positions are 890, 880, 886, 876
+ int[] offsets = new int[4];
+ for (int i = 0; i < bytes.length - 1; ++i) {
+ if (bytes[i] == 0x01) { // high byte
+ for (int j = 0; j < offsets.length; ++j) {
+ if ((offsets[j] == 0) && (bytes[i+1] == (0x11 + j))) { // low byte
+ offsets[j] = i;
+ break;
+ }
+ }
+ }
+ }
+
+ {
+ ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
+ Object o = ois.readObject();
+ ois.close();
+
+ if (!nf.equals(o)) {
+ errln("Fail: NumberFormat serialization/equality bug");
+ } else {
+ logln("NumberFormat serialization/equality is OKAY.");
+ }
+ }
+
+ // Change the values in the byte stream so that min > max.
+ // Numberformat should catch this and throw an exception.
+ for (int i = 0; i < offsets.length; ++i) {
+ bytes[offsets[i]] = (byte)(4 - i);
+ }
+
+ {
+ ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
+ try {
+ NumberFormat format = (NumberFormat) ois.readObject();
+ logln("format: " + format.format(1234.56)); //fix "The variable is never used"
+ errln("FAIL: Deserialized bogus NumberFormat with minXDigits > maxXDigits");
+ } catch (InvalidObjectException e) {
+ logln("Ok: " + e.getMessage());
+ }
+ }
+
+ // Set values so they are too high, but min <= max
+ // Format should pass the min <= max test, and DecimalFormat should reset to current maximum
+ // (for compatibility with versions streamed out before the maximums were imposed).
+ for (int i = 0; i < offsets.length; ++i) {
+ bytes[offsets[i]] = 4;
+ }
+
+ {
+ ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
+ NumberFormat format = (NumberFormat) ois.readObject();
+ //For compatibility with previous version
+ if ((format.getMaximumIntegerDigits() != 309)
+ || format.getMaximumFractionDigits() != 340) {
+ errln("FAIL: Deserialized bogus NumberFormat with values out of range," +
+ " intMin: " + format.getMinimumIntegerDigits() +
+ " intMax: " + format.getMaximumIntegerDigits() +
+ " fracMin: " + format.getMinimumFractionDigits() +
+ " fracMax: " + format.getMaximumFractionDigits());
+ } else {
+ logln("Ok: Digit count out of range");
+ }
+ }
+ }
+
+
+ /**
+ * Some DecimalFormatSymbols changes are not picked up by DecimalFormat.
+ * This includes the minus sign, currency symbol, international currency
+ * symbol, percent, and permille. This is filed as bugs 4212072 and
+ * 4212073.
+ */
+ public void Test4212072() throws IOException, ClassNotFoundException {
+ DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
+ DecimalFormat fmt = new DecimalFormat("#", sym);
+
+ sym.setMinusSign('^');
+ fmt.setDecimalFormatSymbols(sym);
+ if (!fmt.format(-1).equals("^1")) {
+ errln("FAIL: -1 x (minus=^) -> " + fmt.format(-1) +
+ ", exp ^1");
+ }
+ if (!fmt.getNegativePrefix().equals("^")) {
+ errln("FAIL: (minus=^).getNegativePrefix -> " +
+ fmt.getNegativePrefix() + ", exp ^");
+ }
+ sym.setMinusSign('-');
+
+ fmt.applyPattern("#%");
+ sym.setPercent('^');
+ fmt.setDecimalFormatSymbols(sym);
+ if (!fmt.format(0.25).equals("25^")) {
+ errln("FAIL: 0.25 x (percent=^) -> " + fmt.format(0.25) +
+ ", exp 25^");
+ }
+ if (!fmt.getPositiveSuffix().equals("^")) {
+ errln("FAIL: (percent=^).getPositiveSuffix -> " +
+ fmt.getPositiveSuffix() + ", exp ^");
+ }
+ sym.setPercent('%');
+
+ fmt.applyPattern("#\u2030");
+ sym.setPerMill('^');
+ fmt.setDecimalFormatSymbols(sym);
+ if (!fmt.format(0.25).equals("250^")) {
+ errln("FAIL: 0.25 x (permill=^) -> " + fmt.format(0.25) +
+ ", exp 250^");
+ }
+ if (!fmt.getPositiveSuffix().equals("^")) {
+ errln("FAIL: (permill=^).getPositiveSuffix -> " +
+ fmt.getPositiveSuffix() + ", exp ^");
+ }
+ sym.setPerMill('\u2030');
+
+ fmt.applyPattern("\u00A4#.00");
+ sym.setCurrencySymbol("usd");
+ fmt.setDecimalFormatSymbols(sym);
+ if (!fmt.format(12.5).equals("usd12.50")) {
+ errln("FAIL: 12.5 x (currency=usd) -> " + fmt.format(12.5) +
+ ", exp usd12.50");
+ }
+ if (!fmt.getPositivePrefix().equals("usd")) {
+ errln("FAIL: (currency=usd).getPositivePrefix -> " +
+ fmt.getPositivePrefix() + ", exp usd");
+ }
+ sym.setCurrencySymbol("$");
+
+ fmt.applyPattern("\u00A4\u00A4#.00");
+ sym.setInternationalCurrencySymbol("DOL");
+ fmt.setDecimalFormatSymbols(sym);
+ if (!fmt.format(12.5).equals("DOL12.50")) {
+ errln("FAIL: 12.5 x (intlcurrency=DOL) -> " + fmt.format(12.5) +
+ ", exp DOL12.50");
+ }
+ if (!fmt.getPositivePrefix().equals("DOL")) {
+ errln("FAIL: (intlcurrency=DOL).getPositivePrefix -> " +
+ fmt.getPositivePrefix() + ", exp DOL");
+ }
+ sym.setInternationalCurrencySymbol("USD");
+
+ if (VersionInfo.ICU_VERSION == VersionInfo.getInstance(2,2)) {
+ // bug in 2.2 that fails this test
+ // to be fixed in the later versions
+ System.out.println("\n Test skipped for release 2.2");
+ return;
+ }
+
+ // Since the pattern logic has changed, make sure that patterns round
+ // trip properly. Test stream in/out integrity too.
+ Locale[] avail = NumberFormat.getAvailableLocales();
+ for (int i=0; i<avail.length; ++i) {
+ for (int j=0; j<3; ++j) {
+ NumberFormat nf;
+ switch (j) {
+ case 0:
+ nf = NumberFormat.getInstance(avail[i]);
+ break;
+ case 1:
+ nf = NumberFormat.getCurrencyInstance(avail[i]);
+ break;
+ default:
+ nf = NumberFormat.getPercentInstance(avail[i]);
+ break;
+ }
+ DecimalFormat df = (DecimalFormat) nf;
+
+ // Test toPattern/applyPattern round trip
+ String pat = df.toPattern();
+ DecimalFormatSymbols symb = new DecimalFormatSymbols(avail[i]);
+ DecimalFormat f2 = new DecimalFormat(pat, symb);
+ if (!df.equals(f2)) {
+ errln("FAIL: " + avail[i] + " #" + j + " -> \"" + pat +
+ "\" -> \"" + f2.toPattern() + '"');
+ }
+
+ // Test toLocalizedPattern/applyLocalizedPattern round trip
+ pat = df.toLocalizedPattern();
+ try{
+ f2.applyLocalizedPattern(pat);
+
+ String s1 = f2.format(123456);
+ String s2 = df.format(123456);
+ if(!s1.equals(s2)){
+ errln("FAIL: " + avail[i] + " #" + j + " -> localized \"" + s2 +
+ "\" -> \"" + s2 + '"'+ " in locale "+df.getLocale(ULocale.ACTUAL_LOCALE));
+
+ }
+ if (!df.equals(f2)) {
+ errln("FAIL: " + avail[i] + " #" + j + " -> localized \"" + pat +
+ "\" -> \"" + f2.toLocalizedPattern() + '"'+ " in locale "+df.getLocale(ULocale.ACTUAL_LOCALE));
+ errln("s1: "+s1+" s2: "+s2);
+ }
+
+ }catch(IllegalArgumentException ex){
+ errln(ex.getMessage()+" for locale "+ df.getLocale(ULocale.ACTUAL_LOCALE));
+ }
+
+
+ // Test writeObject/readObject round trip
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject(df);
+ oos.flush();
+ baos.close();
+ byte[] bytes = baos.toByteArray();
+ ObjectInputStream ois =
+ new ObjectInputStream(new ByteArrayInputStream(bytes));
+ f2 = (DecimalFormat) ois.readObject();
+ if (!df.equals(f2)) {
+ errln("FAIL: Stream in/out " + avail[i] + " -> \"" + pat +
+ "\" -> " +
+ (f2 != null ? ("\""+f2.toPattern()+'"') : "null"));
+ }
+
+ }
+ }
+
+ // @since ICU 2.4
+ // Make sure that all special characters, when quoted in a suffix or
+ // prefix, lose their special meaning.
+ char[] SPECIALS = { '0', ',', '.', '\u2030', '%', '#',
+ ';', 'E', '*', '+', '-' };
+ sym = new DecimalFormatSymbols(Locale.US);
+ for (int j=0; j<SPECIALS.length; ++j) {
+ char special = SPECIALS[j];
+ String pat = "'" + special + "'#0'" + special + "'";
+ try {
+ fmt = new DecimalFormat(pat, sym);
+ String pat2 = fmt.toPattern();
+ if (!pat.equals(pat2)) {
+ errln("FAIL: Pattern \"" + pat + "\" => toPattern() => \"" +
+ pat2 + "\"");
+ }
+ String s = fmt.format(123);
+ String exp = "" + special + "123" + special;
+ if (!s.equals(exp)) {
+ errln("FAIL: 123 x \"" + pat + "\" => \"" + s + "\", exp \"" +
+ exp + "\"");
+ }
+ } catch (IllegalArgumentException e) {
+ errln("FAIL: Pattern \"" + pat + "\" => " + e.getMessage());
+ }
+ }
+ }
+
+ /**
+ * DecimalFormat.parse() fails for mulipliers 2^n.
+ */
+ public void Test4216742() throws ParseException {
+ DecimalFormat fmt = (DecimalFormat) NumberFormat.getInstance(Locale.US);
+ long[] DATA = { Long.MIN_VALUE, Long.MAX_VALUE, -100000000L, 100000000L};
+ for (int i=0; i<DATA.length; ++i) {
+ String str = Long.toString(DATA[i]);
+ for (int m = 1; m <= 100; m++) {
+ fmt.setMultiplier(m);
+ long n = ((Number) fmt.parse(str)).longValue();
+ if (n > 0 != DATA[i] > 0) {
+ errln("\"" + str + "\" parse(x " + fmt.getMultiplier() +
+ ") => " + n);
+ }
+ }
+ }
+ }
+
+ /**
+ * DecimalFormat formats 1.001 to "1.00" instead of "1" with 2 fraction
+ * digits.
+ */
+ public void Test4217661() {
+ Object[] DATA = {
+ new Double(0.001), "0",
+ new Double(1.001), "1",
+ new Double(0.006), "0.01",
+ new Double(1.006), "1.01",
+ };
+ NumberFormat fmt = NumberFormat.getInstance(Locale.US);
+ fmt.setMaximumFractionDigits(2);
+ for (int i=0; i<DATA.length; i+=2) {
+ String s = fmt.format(((Double) DATA[i]).doubleValue());
+ if (!s.equals(DATA[i+1])) {
+ errln("FAIL: Got " + s + ", exp " + DATA[i+1]);
+ }
+ }
+ }
+
+ /**
+ * 4243011: Formatting .5 rounds to "1" instead of "0"
+ */
+ public void Test4243011() {
+ double DATA[] = {0.5, 1.5, 2.5, 3.5, 4.5};
+ String EXPECTED[] = {"0.", "2.", "2.", "4.", "4."};
+
+ DecimalFormat format = new DecimalFormat("0.");
+ for (int i = 0; i < DATA.length; i++) {
+ String result = format.format(DATA[i]);
+ if (result.equals(EXPECTED[i])) {
+ logln("OK: got " + result);
+ } else {
+ errln("FAIL: got " + result);
+ }
+ }
+ }
+
+ /**
+ * 4243108: format(0.0) gives "0.1" if preceded by parse("99.99")
+ */
+ public void Test4243108() {
+ DecimalFormat f = new DecimalFormat("#.#");
+ String result = f.format(0.0);
+ if (result.equals("0")) {
+ logln("OK: got " + result);
+ } else {
+ errln("FAIL: got " + result);
+ }
+ try {
+ double dResult = f.parse("99.99").doubleValue();
+ if (dResult == 99.99) {
+ logln("OK: got " + dResult);
+ } else {
+ errln("FAIL: got " + dResult);
+ }
+ } catch (ParseException e) {
+ errln("Caught a ParseException:");
+ e.printStackTrace();
+ }
+ result = f.format(0.0);
+ if (result.equals("0")) {
+ logln("OK: got " + result);
+ } else {
+ errln("FAIL: got " + result);
+ }
+ }
+
+ /**
+ * 4330377: DecimalFormat engineering notation gives incorrect results
+ */
+ public void test4330377() {
+ /*
+ double[] input = {5000.0, 500.0, 50.0, 5.0, 0.5, 0.05, 0.005, 0.0005,
+ 5050.0, 505.0, 50.5, 5.05, 0.505, 0.0505, 0.00505, 0.000505};
+ String[] pattern = {"000.#E0", "##0.#E0", "#00.#E0"};
+ String[][] expected = {
+ // it's questionable whether "#00.#E0" should result in post-decimal
+ // zeroes, i.e., whether "5.0E3", "5.0E0", "5.0E-3" are really good
+ {"500E1", "5E3", "5.0E3"},
+ {"500E0", "500E0", "500E0"},
+ {"500E-1", "50E0", "50E0"},
+ {"500E-2", "5E0", "5.0E0"},
+ {"500E-3", "500E-3", "500E-3"},
+ {"500E-4", "50E-3", "50E-3"},
+ {"500E-5", "5E-3", "5.0E-3"},
+ {"500E-6", "500E-6", "500E-6"},
+ {"505E1", "5.05E3", "5.05E3"},
+ {"505E0", "505E0", "505E0"},
+ {"505E-1", "50.5E0", "50.5E0"},
+ {"505E-2", "5.05E0", "5.05E0"},
+ {"505E-3", "505E-3", "505E-3"},
+ {"505E-4", "50.5E-3", "50.5E-3"},
+ {"505E-5", "5.05E-3", "5.05E-3"},
+ {"505E-6", "505E-6", "505E-6"}
+ };
+ for (int i = 0; i < input.length; i++) {
+ for (int j = 0; j < pattern.length; j++) {
+ DecimalFormat format = new DecimalFormat(pattern[j]);
+ String result = format.format(input[i]);
+ if (!result.equals(expected[i][j])) {
+ errln("FAIL: input: " + input[i] +
+ ", pattern: " + pattern[j] +
+ ", expected: " + expected[i][j] +
+ ", got: " + result);
+ }
+ }
+ }
+ */
+ }
+
+ /**
+ * 4233840: NumberFormat does not round correctly
+ */
+ public void test4233840() {
+ float f = 0.0099f;
+
+ NumberFormat nf = new DecimalFormat("0.##", new DecimalFormatSymbols(Locale.US));
+ nf.setMinimumFractionDigits(2);
+
+ String result = nf.format(f);
+
+ if (!result.equals("0.01")) {
+ errln("FAIL: input: " + f + ", expected: 0.01, got: " + result);
+ }
+ }
+
+ /**
+ * 4241880: Decimal format doesnt round a double properly when the number is less than 1
+ */
+ public void test4241880() {
+ Locale savedLocale = Locale.getDefault();
+ Locale.setDefault(Locale.US);
+ double[] input = {
+ .019, .009, .015, .016, .014,
+ .004, .005, .006, .007, .008,
+ .5, 1.5, .05, .15, .005,
+ .015, .0005, .0015,
+ };
+ String[] pattern = {
+ "##0%", "##0%", "##0%", "##0%", "##0%",
+ "##0%", "##0%", "##0%", "##0%", "##0%",
+ "#,##0", "#,##0", "#,##0.0", "#,##0.0", "#,##0.00",
+ "#,##0.00", "#,##0.000", "#,##0.000",
+ };
+ String[] expected = {
+ "2%", "1%", "2%", "2%", "1%",
+ "0%", "0%", "1%", "1%", "1%",
+ "0", "2", "0.0", "0.2", "0.00",
+ "0.02", "0.000", "0.002",
+ };
+ for (int i = 0; i < input.length; i++) {
+ DecimalFormat format = new DecimalFormat(pattern[i]);
+ String result = format.format(input[i]);
+ if (!result.equals(expected[i])) {
+ errln("FAIL: input: " + input[i] +
+ ", pattern: " + pattern[i] +
+ ", expected: " + expected[i] +
+ ", got: " + result);
+ }
+ }
+ Locale.setDefault(savedLocale);
+ }
+}
+
+class myformat implements Serializable
+{
+ /**
+ * For serialization
+ */
+ private static final long serialVersionUID = 4120813612616076506L;
+ DateFormat _dateFormat = DateFormat.getDateInstance();
+
+ public String Now()
+ {
+ GregorianCalendar calendar = new GregorianCalendar();
+ Date t = calendar.getTime();
+ String nowStr = _dateFormat.format(t);
+ return nowStr;
+ }
+}
+
+class MyNumberFormatTest extends NumberFormat {
+ /**
+ * For serialization
+ */
+ private static final long serialVersionUID = 1251303884737169952L;
+ public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {
+ return new StringBuffer("");
+ }
+ public StringBuffer format(long number,StringBuffer toAppendTo, FieldPosition pos) {
+ return new StringBuffer("");
+ }
+ public Number parse(String text, ParsePosition parsePosition) {
+ return new Integer(0);
+ }
+//#if defined(FOUNDATION10)
+//#else
+ public StringBuffer format(java.math.BigDecimal number, StringBuffer toAppendTo, FieldPosition pos) {
+ return new StringBuffer("");
+ }
+//#endif
+ public StringBuffer format(BigInteger number, StringBuffer toAppendTo, FieldPosition pos) {
+ return new StringBuffer("");
+ }
+ public StringBuffer format(com.ibm.icu.math.BigDecimal number, StringBuffer toAppendTo, FieldPosition pos) {
+ return new StringBuffer("");
+ }
+}
+