ICU-92 NumberFormat test porting and bug fixing

X-SVN-Rev: 6331
This commit is contained in:
GCL Shanghai 2001-10-19 12:17:39 +00:00
parent 0d85c6fd9a
commit e256b77c06
20 changed files with 8282 additions and 0 deletions

View File

@ -0,0 +1,236 @@
/*****************************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/dev/test/format/IntlTestDecimalFormatAPI.java,v $
* $Date: 2001/10/19 12:09:26 $
* $Revision: 1.1 $
*
*****************************************************************************************
**/
/**
* Port From: JDK 1.4b1 : java.text.Format.IntlTestDecimalFormatAPI
* Source File: java/text/format/IntlTestDecimalFormatAPI.java
**/
/*
@test 1.4 98/03/06
@summary test International Decimal Format API
*/
/*
(C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
(C) Copyright IBM Corp. 1996, 1997, 2001 - All Rights Reserved
The original version of this source code and documentation is copyrighted and
owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These materials are
provided under terms of a License Agreement between Taligent and Sun. This
technology is protected by multiple US and International patents. This notice and
attribution to Taligent may not be removed.
Taligent is a registered trademark of Taligent, Inc.
*/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
import java.text.ParsePosition;
import java.text.Format;
import java.text.FieldPosition;
public class IntlTestDecimalFormatAPI extends com.ibm.test.TestFmwk
{
public static void main(String[] args) throws Exception {
new IntlTestDecimalFormatAPI().run(args);
}
// This test checks various generic API methods in DecimalFormat to achieve 100% API coverage.
public void TestAPI()
{
logln("DecimalFormat API test---"); logln("");
Locale.setDefault(Locale.ENGLISH);
// ======= Test constructors
logln("Testing DecimalFormat constructors");
DecimalFormat def = new DecimalFormat();
final String pattern = new String("#,##0.# FF");
DecimalFormat pat = null;
try {
pat = new DecimalFormat(pattern);
}
catch (IllegalArgumentException e) {
errln("ERROR: Could not create DecimalFormat (pattern)");
}
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.FRENCH);
DecimalFormat cust1 = new DecimalFormat(pattern, symbols);
// ======= Test clone(), assignment, and equality
logln("Testing clone() and equality operators");
Format clone = (Format) def.clone();
if( ! def.equals(clone)) {
errln("ERROR: Clone() failed");
}
// ======= Test various format() methods
logln("Testing various format() methods");
// final double d = -10456.0037; // this appears as -10456.003700000001 on NT
// final double d = -1.04560037e-4; // this appears as -1.0456003700000002E-4 on NT
final double d = -10456.00370000000000; // this works!
final long l = 100000000;
logln("" + d + " is the double value");
StringBuffer res1 = new StringBuffer();
StringBuffer res2 = new StringBuffer();
StringBuffer res3 = new StringBuffer();
StringBuffer res4 = new StringBuffer();
FieldPosition pos1 = new FieldPosition(0);
FieldPosition pos2 = new FieldPosition(0);
FieldPosition pos3 = new FieldPosition(0);
FieldPosition pos4 = new FieldPosition(0);
res1 = def.format(d, res1, pos1);
logln("" + d + " formatted to " + res1);
res2 = pat.format(l, res2, pos2);
logln("" + l + " formatted to " + res2);
res3 = cust1.format(d, res3, pos3);
logln("" + d + " formatted to " + res3);
res4 = cust1.format(l, res4, pos4);
logln("" + l + " formatted to " + res4);
// ======= Test parse()
logln("Testing parse()");
String text = new String("-10,456.0037");
ParsePosition pos = new ParsePosition(0);
String patt = new String("#,##0.#");
pat.applyPattern(patt);
double d2 = pat.parse(text, pos).doubleValue();
if(d2 != d) {
errln("ERROR: Roundtrip failed (via parse(" + d2 + " != " + d + ")) for " + text);
}
logln(text + " parsed into " + (long) d2);
// ======= Test getters and setters
logln("Testing getters and setters");
final DecimalFormatSymbols syms = pat.getDecimalFormatSymbols();
def.setDecimalFormatSymbols(syms);
if( ! pat.getDecimalFormatSymbols().equals(def.getDecimalFormatSymbols())) {
errln("ERROR: set DecimalFormatSymbols() failed");
}
String posPrefix;
pat.setPositivePrefix("+");
posPrefix = pat.getPositivePrefix();
logln("Positive prefix (should be +): " + posPrefix);
if(posPrefix != "+") {
errln("ERROR: setPositivePrefix() failed");
}
String negPrefix;
pat.setNegativePrefix("-");
negPrefix = pat.getNegativePrefix();
logln("Negative prefix (should be -): " + negPrefix);
if(negPrefix != "-") {
errln("ERROR: setNegativePrefix() failed");
}
String posSuffix;
pat.setPositiveSuffix("_");
posSuffix = pat.getPositiveSuffix();
logln("Positive suffix (should be _): " + posSuffix);
if(posSuffix != "_") {
errln("ERROR: setPositiveSuffix() failed");
}
String negSuffix;
pat.setNegativeSuffix("~");
negSuffix = pat.getNegativeSuffix();
logln("Negative suffix (should be ~): " + negSuffix);
if(negSuffix != "~") {
errln("ERROR: setNegativeSuffix() failed");
}
long multiplier = 0;
pat.setMultiplier(8);
multiplier = pat.getMultiplier();
logln("Multiplier (should be 8): " + multiplier);
if(multiplier != 8) {
errln("ERROR: setMultiplier() failed");
}
int groupingSize = 0;
pat.setGroupingSize(2);
groupingSize = pat.getGroupingSize();
logln("Grouping size (should be 2): " + (long) groupingSize);
if(groupingSize != 2) {
errln("ERROR: setGroupingSize() failed");
}
pat.setDecimalSeparatorAlwaysShown(true);
boolean tf = pat.isDecimalSeparatorAlwaysShown();
logln("DecimalSeparatorIsAlwaysShown (should be true) is " + (tf ? "true" : "false"));
if(tf != true) {
errln("ERROR: setDecimalSeparatorAlwaysShown() failed");
}
String funkyPat;
funkyPat = pat.toPattern();
logln("Pattern is " + funkyPat);
String locPat;
locPat = pat.toLocalizedPattern();
logln("Localized pattern is " + locPat);
// ======= Test applyPattern()
logln("Testing applyPattern()");
String p1 = new String("#,##0.0#;(#,##0.0#)");
logln("Applying pattern " + p1);
pat.applyPattern(p1);
String s2;
s2 = pat.toPattern();
logln("Extracted pattern is " + s2);
if( ! s2.equals(p1) ) {
errln("ERROR: toPattern() result did not match pattern applied");
}
String p2 = new String("#,##0.0# FF;(#,##0.0# FF)");
logln("Applying pattern " + p2);
pat.applyLocalizedPattern(p2);
String s3;
s3 = pat.toLocalizedPattern();
logln("Extracted pattern is " + s3);
if( ! s3.equals(p2) ) {
errln("ERROR: toLocalizedPattern() result did not match pattern applied");
}
// ======= Test getStaticClassID()
// logln("Testing instanceof()");
// try {
// NumberFormat test = new DecimalFormat();
// if (! (test instanceof DecimalFormat)) {
// errln("ERROR: instanceof failed");
// }
// }
// catch (Exception e) {
// errln("ERROR: Couldn't create a DecimalFormat");
// }
}
}

View File

@ -0,0 +1,287 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/dev/test/format/IntlTestDecimalFormatAPIC.java,v $
* $Date: 2001/10/19 12:10:26 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : IntlTestDecimalFormatAPI
* Source File: $ICU4CRoot/source/test/intltest/dcfmapts.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.util.*;
import java.util.Locale;
import java.text.ParsePosition;
import java.text.Format;
import com.ibm.text.*;
import java.text.FieldPosition;
// This is an API test, not a unit test. It doesn't test very many cases, and doesn't
// try to test the full functionality. It just calls each function in the class and
// verifies that it works on a basic level.
public class IntlTestDecimalFormatAPIC extends com.ibm.test.TestFmwk {
public static void main(String[] args) throws Exception {
new IntlTestDecimalFormatAPIC().run(args);
}
// This test checks various generic API methods in DecimalFormat to achieve 100% API coverage.
public void TestAPI() {
logln("DecimalFormat API test---");
logln("");
Locale.setDefault(Locale.ENGLISH);
// ======= Test constructors
logln("Testing DecimalFormat constructors");
DecimalFormat def = new DecimalFormat();
final String pattern = new String("#,##0.# FF");
DecimalFormat pat = null;
try {
pat = new DecimalFormat(pattern);
} catch (IllegalArgumentException e) {
errln("ERROR: Could not create DecimalFormat (pattern)");
}
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.FRENCH);
DecimalFormat cust1 = new DecimalFormat(pattern, symbols);
// ======= Test clone(), assignment, and equality
logln("Testing clone() and equality operators");
Format clone = (Format) def.clone();
if (!def.equals(clone)) {
errln("ERROR: Clone() failed");
}
// ======= Test various format() methods
logln("Testing various format() methods");
// final double d = -10456.0037; // this appears as -10456.003700000001 on NT
// final double d = -1.04560037e-4; // this appears as -1.0456003700000002E-4 on NT
final double d = -10456.00370000000000; // this works!
final long l = 100000000;
logln("" + Double.toString(d) + " is the double value");
StringBuffer res1 = new StringBuffer();
StringBuffer res2 = new StringBuffer();
StringBuffer res3 = new StringBuffer();
StringBuffer res4 = new StringBuffer();
FieldPosition pos1 = new FieldPosition(0);
FieldPosition pos2 = new FieldPosition(0);
FieldPosition pos3 = new FieldPosition(0);
FieldPosition pos4 = new FieldPosition(0);
res1 = def.format(d, res1, pos1);
logln("" + Double.toString(d) + " formatted to " + res1);
res2 = pat.format(l, res2, pos2);
logln("" + l + " formatted to " + res2);
res3 = cust1.format(d, res3, pos3);
logln("" + Double.toString(d) + " formatted to " + res3);
res4 = cust1.format(l, res4, pos4);
logln("" + l + " formatted to " + res4);
// ======= Test parse()
logln("Testing parse()");
String text = new String("-10,456.0037");
ParsePosition pos = new ParsePosition(0);
String patt = new String("#,##0.#");
pat.applyPattern(patt);
double d2 = pat.parse(text, pos).doubleValue();
if (d2 != d) {
errln(
"ERROR: Roundtrip failed (via parse(" + Double.toString(d2) + " != " + Double.toString(d) + ")) for " + text);
}
logln(text + " parsed into " + (long) d2);
// ======= Test getters and setters
logln("Testing getters and setters");
final DecimalFormatSymbols syms = pat.getDecimalFormatSymbols();
def.setDecimalFormatSymbols(syms);
if (!pat.getDecimalFormatSymbols().equals(def.getDecimalFormatSymbols())) {
errln("ERROR: set DecimalFormatSymbols() failed");
}
String posPrefix;
pat.setPositivePrefix("+");
posPrefix = pat.getPositivePrefix();
logln("Positive prefix (should be +): " + posPrefix);
if (posPrefix != "+") {
errln("ERROR: setPositivePrefix() failed");
}
String negPrefix;
pat.setNegativePrefix("-");
negPrefix = pat.getNegativePrefix();
logln("Negative prefix (should be -): " + negPrefix);
if (negPrefix != "-") {
errln("ERROR: setNegativePrefix() failed");
}
String posSuffix;
pat.setPositiveSuffix("_");
posSuffix = pat.getPositiveSuffix();
logln("Positive suffix (should be _): " + posSuffix);
if (posSuffix != "_") {
errln("ERROR: setPositiveSuffix() failed");
}
String negSuffix;
pat.setNegativeSuffix("~");
negSuffix = pat.getNegativeSuffix();
logln("Negative suffix (should be ~): " + negSuffix);
if (negSuffix != "~") {
errln("ERROR: setNegativeSuffix() failed");
}
long multiplier = 0;
pat.setMultiplier(8);
multiplier = pat.getMultiplier();
logln("Multiplier (should be 8): " + multiplier);
if (multiplier != 8) {
errln("ERROR: setMultiplier() failed");
}
int groupingSize = 0;
pat.setGroupingSize(2);
groupingSize = pat.getGroupingSize();
logln("Grouping size (should be 2): " + (long) groupingSize);
if (groupingSize != 2) {
errln("ERROR: setGroupingSize() failed");
}
pat.setDecimalSeparatorAlwaysShown(true);
boolean tf = pat.isDecimalSeparatorAlwaysShown();
logln(
"DecimalSeparatorIsAlwaysShown (should be true) is " + (tf ? "true" : "false"));
if (tf != true) {
errln("ERROR: setDecimalSeparatorAlwaysShown() failed");
}
String funkyPat;
funkyPat = pat.toPattern();
logln("Pattern is " + funkyPat);
String locPat;
locPat = pat.toLocalizedPattern();
logln("Localized pattern is " + locPat);
// ======= Test applyPattern()
logln("Testing applyPattern()");
String p1 = new String("#,##0.0#;(#,##0.0#)");
logln("Applying pattern " + p1);
pat.applyPattern(p1);
String s2;
s2 = pat.toPattern();
logln("Extracted pattern is " + s2);
if (!s2.equals(p1)) {
errln("ERROR: toPattern() result did not match pattern applied");
}
String p2 = new String("#,##0.0# FF;(#,##0.0# FF)");
logln("Applying pattern " + p2);
pat.applyLocalizedPattern(p2);
String s3;
s3 = pat.toLocalizedPattern();
logln("Extracted pattern is " + s3);
if (!s3.equals(p2)) {
errln("ERROR: toLocalizedPattern() result did not match pattern applied");
}
// ======= Test getStaticClassID()
// logln("Testing instanceof()");
// try {
// NumberFormat test = new DecimalFormat();
// if (! (test instanceof DecimalFormat)) {
// errln("ERROR: instanceof failed");
// }
// }
// catch (Exception e) {
// errln("ERROR: Couldn't create a DecimalFormat");
// }
}
public void TestRounding() {
double Roundingnumber = 2.55;
double Roundingnumber1 = -2.55;
//+2.55 results -2.55 results
double result[] = {
3, -3,
2, -2,
3, -2,
2, -3,
3, -3,
3, -3,
3, -3
};
DecimalFormat pat = new DecimalFormat();
String s = "";
s = pat.toPattern();
logln("pattern = " + s);
int mode;
int i = 0;
String message;
String resultStr;
for (mode = 0; mode < 7; mode++) {
pat.setRoundingMode(mode);
if (pat.getRoundingMode() != mode) {
errln(
"SetRoundingMode or GetRoundingMode failed for mode=" + mode);
}
//for +2.55 with RoundingIncrement=1.0
pat.setRoundingIncrement(1.0);
resultStr = pat.format(Roundingnumber);
message = "round(" + (double) Roundingnumber
+ "," + mode + ",FALSE) with RoundingIncrement=1.0==>";
verify(message, resultStr, result[i++]);
message = "";
resultStr = "";
//for -2.55 with RoundingIncrement=1.0
resultStr = pat.format(Roundingnumber1);
message = "round(" + (double) Roundingnumber1
+ "," + mode + ",FALSE) with RoundingIncrement=1.0==>";
verify(message, resultStr, result[i++]);
message = "";
resultStr = "";
}
}
/*Helper functions */
public void verify(String message, String got, double expected) {
logln(message + got + " Expected : " + (long)expected);
String expectedStr = "";
expectedStr=expectedStr + (long)expected;
if(!got.equals(expectedStr) ) {
errln("ERROR: Round() failed: " + message + got + " Expected : " + expectedStr);
}
}
}

View File

@ -0,0 +1,132 @@
/*****************************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/dev/test/format/IntlTestDecimalFormatSymbols.java,v $
* $Date: 2001/10/19 12:11:07 $
* $Revision: 1.1 $
*
*****************************************************************************************
**/
/**
* Port From: JDK 1.4b1 : java.text.Format.IntlTestDecimalFormatSymbols
* Source File: java/text/format/IntlTestDecimalFormatSymbols.java
**/
/*
@test 1.4 98/03/06
@summary test International Decimal Format Symbols
*/
/*
(C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
(C) Copyright IBM Corp. 1996, 1997, 2001 - All Rights Reserved
The original version of this source code and documentation is copyrighted and
owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These materials are
provided under terms of a License Agreement between Taligent and Sun. This
technology is protected by multiple US and International patents. This notice and
attribution to Taligent may not be removed.
Taligent is a registered trademark of Taligent, Inc.
*/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
import java.text.FieldPosition;
public class IntlTestDecimalFormatSymbols extends com.ibm.test.TestFmwk
{
public static void main(String[] args) throws Exception {
new IntlTestDecimalFormatSymbols().run(args);
}
// Test the API of DecimalFormatSymbols; primarily a simple get/set set.
public void TestSymbols()
{
DecimalFormatSymbols fr = new DecimalFormatSymbols(Locale.FRENCH);
DecimalFormatSymbols en = new DecimalFormatSymbols(Locale.ENGLISH);
if(en.equals(fr)) {
errln("ERROR: English DecimalFormatSymbols equal to French");
}
// just do some VERY basic tests to make sure that get/set work
char zero = en.getZeroDigit();
fr.setZeroDigit(zero);
if(fr.getZeroDigit() != en.getZeroDigit()) {
errln("ERROR: get/set ZeroDigit failed");
}
char group = en.getGroupingSeparator();
fr.setGroupingSeparator(group);
if(fr.getGroupingSeparator() != en.getGroupingSeparator()) {
errln("ERROR: get/set GroupingSeparator failed");
}
char decimal = en.getDecimalSeparator();
fr.setDecimalSeparator(decimal);
if(fr.getDecimalSeparator() != en.getDecimalSeparator()) {
errln("ERROR: get/set DecimalSeparator failed");
}
char perMill = en.getPerMill();
fr.setPerMill(perMill);
if(fr.getPerMill() != en.getPerMill()) {
errln("ERROR: get/set PerMill failed");
}
char percent = en.getPercent();
fr.setPercent(percent);
if(fr.getPercent() != en.getPercent()) {
errln("ERROR: get/set Percent failed");
}
char digit = en.getDigit();
fr.setDigit(digit);
if(fr.getPercent() != en.getPercent()) {
errln("ERROR: get/set Percent failed");
}
char patternSeparator = en.getPatternSeparator();
fr.setPatternSeparator(patternSeparator);
if(fr.getPatternSeparator() != en.getPatternSeparator()) {
errln("ERROR: get/set PatternSeparator failed");
}
String infinity = en.getInfinity();
fr.setInfinity(infinity);
String infinity2 = fr.getInfinity();
if(! infinity.equals(infinity2)) {
errln("ERROR: get/set Infinity failed");
}
String nan = en.getNaN();
fr.setNaN(nan);
String nan2 = fr.getNaN();
if(! nan.equals(nan2)) {
errln("ERROR: get/set NaN failed");
}
char minusSign = en.getMinusSign();
fr.setMinusSign(minusSign);
if(fr.getMinusSign() != en.getMinusSign()) {
errln("ERROR: get/set MinusSign failed");
}
// char exponential = en.getExponentialSymbol();
// fr.setExponentialSymbol(exponential);
// if(fr.getExponentialSymbol() != en.getExponentialSymbol()) {
// errln("ERROR: get/set Exponential failed");
// }
DecimalFormatSymbols foo = new DecimalFormatSymbols();
en = (DecimalFormatSymbols) fr.clone();
if(! en.equals(fr)) {
errln("ERROR: Clone failed");
}
}
}

View File

@ -0,0 +1,147 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/dev/test/format/IntlTestDecimalFormatSymbolsC.java,v $
* $Date: 2001/10/19 12:11:59 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : IntlTestDecimalFormatSymbols
* Source File: $ICU4CRoot/source/test/intltest/tsdcfmsy.cpp
**/
package com.ibm.icu.test.format;
import java.text.FieldPosition;
import com.ibm.util.*;
import java.util.Locale;
import com.ibm.text.*;
/**
* Tests for DecimalFormatSymbols
**/
public class IntlTestDecimalFormatSymbolsC extends com.ibm.test.TestFmwk {
public static void main(String[] args) throws Exception {
new IntlTestDecimalFormatSymbolsC().run(args);
}
/**
* Test the API of DecimalFormatSymbols; primarily a simple get/set set.
*/
public void TestSymbols() {
DecimalFormatSymbols fr = new DecimalFormatSymbols(Locale.FRENCH);
DecimalFormatSymbols en = new DecimalFormatSymbols(Locale.ENGLISH);
if (en.equals(fr)) {
errln("ERROR: English DecimalFormatSymbols equal to French");
}
// just do some VERY basic tests to make sure that get/set work
char zero = en.getZeroDigit();
fr.setZeroDigit(zero);
if (fr.getZeroDigit() != en.getZeroDigit()) {
errln("ERROR: get/set ZeroDigit failed");
}
char group = en.getGroupingSeparator();
fr.setGroupingSeparator(group);
if (fr.getGroupingSeparator() != en.getGroupingSeparator()) {
errln("ERROR: get/set GroupingSeparator failed");
}
char decimal = en.getDecimalSeparator();
fr.setDecimalSeparator(decimal);
if (fr.getDecimalSeparator() != en.getDecimalSeparator()) {
errln("ERROR: get/set DecimalSeparator failed");
}
char perMill = en.getPerMill();
fr.setPerMill(perMill);
if (fr.getPerMill() != en.getPerMill()) {
errln("ERROR: get/set PerMill failed");
}
char percent = en.getPercent();
fr.setPercent(percent);
if (fr.getPercent() != en.getPercent()) {
errln("ERROR: get/set Percent failed");
}
char digit = en.getDigit();
fr.setDigit(digit);
if (fr.getPercent() != en.getPercent()) {
errln("ERROR: get/set Percent failed");
}
char patternSeparator = en.getPatternSeparator();
fr.setPatternSeparator(patternSeparator);
if (fr.getPatternSeparator() != en.getPatternSeparator()) {
errln("ERROR: get/set PatternSeparator failed");
}
String infinity = en.getInfinity();
fr.setInfinity(infinity);
String infinity2 = fr.getInfinity();
if (!infinity.equals(infinity2)) {
errln("ERROR: get/set Infinity failed");
}
String nan = en.getNaN();
fr.setNaN(nan);
String nan2 = fr.getNaN();
if (!nan.equals(nan2)) {
errln("ERROR: get/set NaN failed");
}
char minusSign = en.getMinusSign();
fr.setMinusSign(minusSign);
if (fr.getMinusSign() != en.getMinusSign()) {
errln("ERROR: get/set MinusSign failed");
}
// char exponential = en.getExponentialSymbol();
// fr.setExponentialSymbol(exponential);
// if(fr.getExponentialSymbol() != en.getExponentialSymbol()) {
// errln("ERROR: get/set Exponential failed");
// }
DecimalFormatSymbols foo = new DecimalFormatSymbols();
en = (DecimalFormatSymbols) fr.clone();
if (!en.equals(fr)) {
errln("ERROR: Clone failed");
}
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
verify(34.5, "00.00", sym, "34.50");
sym.setDecimalSeparator('S');
verify(34.5, "00.00", sym, "34S50");
sym.setPercent('P');
verify(34.5, "00 %", sym, "3450 P");
sym.setCurrencySymbol("D");
verify(34.5, "\u00a4##.##", sym, "D34.5");
sym.setGroupingSeparator('|');
verify(3456.5, "0,000.##", sym, "3|456S5");
}
/** helper functions**/
public void verify(double value, String pattern, DecimalFormatSymbols sym, String expected) {
DecimalFormat df = new DecimalFormat(pattern, sym);
StringBuffer buffer = new StringBuffer("");
FieldPosition pos = new FieldPosition(-1);
buffer = df.format(value, buffer, pos);
if(!buffer.toString().equals(expected)){
errln("ERROR: format failed after setSymbols()\n Expected" +
expected + ", Got " + buffer);
}
}
}

View File

@ -0,0 +1,292 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/dev/test/format/IntlTestNumberFormat.java,v $
* $Date: 2001/10/19 12:12:47 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : IntlTestNumberFormat
* Source File: $ICU4CRoot/source/test/intltest/tsnmfmt.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
/**
* This test does round-trip testing (format -> parse -> format -> parse -> etc.) of
* NumberFormat.
*/
public class IntlTestNumberFormat extends com.ibm.test.TestFmwk {
public NumberFormat fNumberFormat = NumberFormat.getInstance();
public static void main(String[] args) throws Exception {
new IntlTestNumberFormat().run(args);
}
/*
* Internal use
**/
public void _testLocale(java.util.Locale locale, String localeName) {
String name;
// locale = java.util.Locale.getDefault();
// localeName = locale.getDisplayName();
name = "Number test";
logln(name + " ( " + localeName + " ) ");
fNumberFormat = NumberFormat.getInstance(locale);
TestFormat();
name = "Currency test";
logln(name + " (" + localeName + ")");
fNumberFormat = NumberFormat.getCurrencyInstance(locale);
TestFormat(/* par */);
name = "Percent test";
logln(name + " (" + localeName + ")");
fNumberFormat = NumberFormat.getPercentInstance(locale);
TestFormat(/* par */);
}
/**
* call TestFormat for currency, percent and plain number instances
**/
public void TestLocale() {
String name;
String localeName;
java.util.Locale locale = java.util.Locale.getDefault();
localeName = locale.getDisplayName();
name = "Number test";
logln(name + " ( " + localeName + " ) ");
fNumberFormat = NumberFormat.getInstance();
TestFormat();
name = "Currency test";
logln(name + " (" + localeName + ")");
fNumberFormat = NumberFormat.getCurrencyInstance();
TestFormat(/* par */);
name = "Percent test";
logln(name + " (" + localeName + ")");
fNumberFormat = NumberFormat.getPercentInstance();
TestFormat(/* par */);
}
/**
* call tryIt with many variations, called by testLocale
**/
public void TestFormat() {
if (fNumberFormat == null){
errln("**** FAIL: Null format returned by createXxxInstance.");
return;
}
DecimalFormat s = (DecimalFormat)fNumberFormat;
logln("pattern :" + s.toPattern());
tryIt(-2.02147304840132e-68);
tryIt(3.88057859588817e-68);
tryIt(-2.64651110485945e+65);
tryIt(9.29526819488338e+64);
tryIt(-2.02147304840132e-100);
tryIt(3.88057859588817e-096);
tryIt(-2.64651110485945e+306);
tryIt(9.29526819488338e+250);
tryIt(-9.18228054496402e+64);
tryIt(-9.69413034454191e+64);
tryIt(-9.18228054496402e+255);
tryIt(-9.69413034454191e+273);
tryIt(1.234e-200);
tryIt(-2.3e-168);
tryIt(Double.NaN);
tryIt(Double.POSITIVE_INFINITY);
tryIt(Double.NEGATIVE_INFINITY);
tryIt(251887531);
tryIt(5e-20 / 9);
tryIt(5e20 / 9);
tryIt(1.234e-50);
tryIt(9.99999999999996);
tryIt(9.999999999999996);
tryIt(Integer.MIN_VALUE);
tryIt(Integer.MAX_VALUE);
tryIt((double)Integer.MIN_VALUE);
tryIt((double)Integer.MAX_VALUE);
tryIt((double)Integer.MIN_VALUE - 1.0);
tryIt((double)Integer.MAX_VALUE + 1.0);
tryIt(5.0 / 9.0 * 1e-20);
tryIt(4.0 / 9.0 * 1e-20);
tryIt(5.0 / 9.0 * 1e+20);
tryIt(4.0 / 9.0 * 1e+20);
tryIt(2147483647.);
tryIt(0);
tryIt(0.0);
tryIt(1);
tryIt(10);
tryIt(100);
tryIt(-1);
tryIt(-10);
tryIt(-100);
tryIt(-1913860352);
for (int j = 0; j < 10; j++) {
double d = Math.random()*2e10 - 1e10;
tryIt(d);
}
}
/**
* perform tests using aNumber and fNumberFormat, called in many variations
**/
public void tryIt(double aNumber) {
final int DEPTH = 10;
double[] number = new double[DEPTH];
String[] string = new String[DEPTH];
int numberMatch = 0;
int stringMatch = 0;
boolean dump = false;
int i;
for (i = 0; i < DEPTH; i++) {
if (i == 0) {
number[i] = aNumber;
} else {
try {
number[i - 1] = fNumberFormat.parse(string[i - 1]).doubleValue();
} catch(java.text.ParseException pe) {
errln("**** FAIL: Parse of " + string[i-1] + " failed.");
dump = true;
break;
}
}
string[i] = fNumberFormat.format(number[i]);
if (i > 0)
{
if (numberMatch == 0 && number[i] == number[i-1])
numberMatch = i;
else if (numberMatch > 0 && number[i] != number[i-1])
{
errln("**** FAIL: Numeric mismatch after match.");
dump = true;
break;
}
if (stringMatch == 0 && string[i] == string[i-1])
stringMatch = i;
else if (stringMatch > 0 && string[i] != string[i-1])
{
errln("**** FAIL: String mismatch after match.");
dump = true;
break;
}
}
if (numberMatch > 0 && stringMatch > 0)
break;
if (i == DEPTH)
--i;
if (stringMatch > 2 || numberMatch > 2)
{
errln("**** FAIL: No string and/or number match within 2 iterations.");
dump = true;
}
if (dump)
{
for (int k=0; k<=i; ++k)
{
logln(k + ": " + number[k] + " F> " +
string[k] + " P> ");
}
}
}
}
/**
* perform tests using aNumber and fNumberFormat, called in many variations
**/
public void tryIt(int aNumber) {
long number;;
String stringNum = fNumberFormat.format(aNumber);
try {
number = fNumberFormat.parse(stringNum).longValue();
} catch (java.text.ParseException pe) {
errln("**** FAIL: Parse of " + stringNum + " failed.");
return;
}
if (number != aNumber) {
errln("**** FAIL: Parse of " + stringNum + " failed. Got:" + number
+ " Expected:" + aNumber);
}
}
/**
* test NumberFormat::getAvailableLocales
**/
public void TestAvailableLocales() {
final java.util.Locale[] locales = NumberFormat.getAvailableLocales();
int count = locales.length;
logln(count + " available locales");
if (count != 0)
{
String name;
String all = "";
for (int i = 0; i< count; ++i)
{
if (i!=0)
all += ", ";
all += locales[i].getDisplayName();
}
logln(all);
}
else
errln("**** FAIL: Zero available locales or null array pointer");
}
/**
* call testLocale for all locales
**/
public void TestMonster() {
final String SEP = "============================================================\n";
int count;
final java.util.Locale[] locales = NumberFormat.getAvailableLocales();
count = locales.length;
if (count != 0)
{
count = 3; // just test 3 locales
for (int i=0; i<count; ++i)
{
String name = locales[i].getDisplayName();
logln(SEP);
_testLocale(/* par, */locales[i], name);
}
}
logln(SEP);
}
}

View File

@ -0,0 +1,209 @@
/*****************************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/dev/test/format/IntlTestNumberFormatAPI.java,v $
* $Date: 2001/10/19 12:13:23 $
* $Revision: 1.1 $
*
*****************************************************************************************
**/
/**
* Port From: JDK 1.4b1 : java.text.Format.IntlTestNumberFormatAPI
* Source File: java/text/format/IntlTestNumberFormatAPI.java
**/
/*
@test 1.4 98/03/06
@summary test International Number Format API
*/
/*
(C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
(C) Copyright IBM Corp. 1996, 1997, 2001 - All Rights Reserved
The original version of this source code and documentation is copyrighted and
owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These materials are
provided under terms of a License Agreement between Taligent and Sun. This
technology is protected by multiple US and International patents. This notice and
attribution to Taligent may not be removed.
Taligent is a registered trademark of Taligent, Inc.
*/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.ParseException;
public class IntlTestNumberFormatAPI extends com.ibm.test.TestFmwk
{
public static void main(String[] args) throws Exception {
new IntlTestNumberFormatAPI().run(args);
}
// This test checks various generic API methods in DecimalFormat to achieve 100% API coverage.
public void TestAPI()
{
logln("NumberFormat API test---"); logln("");
Locale.setDefault(Locale.ENGLISH);
// ======= Test constructors
logln("Testing NumberFormat constructors");
NumberFormat def = NumberFormat.getInstance();
NumberFormat fr = NumberFormat.getInstance(Locale.FRENCH);
NumberFormat cur = NumberFormat.getCurrencyInstance();
NumberFormat cur_fr = NumberFormat.getCurrencyInstance(Locale.FRENCH);
NumberFormat per = NumberFormat.getPercentInstance();
NumberFormat per_fr = NumberFormat.getPercentInstance(Locale.FRENCH);
NumberFormat integer = NumberFormat.getIntegerInstance();
NumberFormat int_fr = NumberFormat.getIntegerInstance(Locale.FRENCH);
// ======= Test equality
logln("Testing equality operator");
if( per_fr.equals(cur_fr) ) {
errln("ERROR: == failed");
}
// ======= Test various format() methods
logln("Testing various format() methods");
// final double d = -10456.0037; // this appears as -10456.003700000001 on NT
// final double d = -1.04560037e-4; // this appears as -1.0456003700000002E-4 on NT
final double d = -10456.00370000000000; // this works!
final long l = 100000000;
String res1 = new String();
String res2 = new String();
StringBuffer res3 = new StringBuffer();
StringBuffer res4 = new StringBuffer();
StringBuffer res5 = new StringBuffer();
StringBuffer res6 = new StringBuffer();
FieldPosition pos1 = new FieldPosition(0);
FieldPosition pos2 = new FieldPosition(0);
FieldPosition pos3 = new FieldPosition(0);
FieldPosition pos4 = new FieldPosition(0);
res1 = cur_fr.format(d);
logln( "" + d + " formatted to " + res1);
res2 = cur_fr.format(l);
logln("" + l + " formatted to " + res2);
res3 = cur_fr.format(d, res3, pos1);
logln( "" + d + " formatted to " + res3);
res4 = cur_fr.format(l, res4, pos2);
logln("" + l + " formatted to " + res4);
res5 = cur_fr.format(d, res5, pos3);
logln("" + d + " formatted to " + res5);
res6 = cur_fr.format(l, res6, pos4);
logln("" + l + " formatted to " + res6);
// ======= Test parse()
logln("Testing parse()");
// String text = new String("-10,456.0037");
String text = new String("-10456,0037");
ParsePosition pos = new ParsePosition(0);
ParsePosition pos01 = new ParsePosition(0);
double d1 = ((Number)fr.parseObject(text, pos)).doubleValue();
if(d1 != d) {
errln("ERROR: Roundtrip failed (via parse()) for " + text);
}
logln(text + " parsed into " + d1);
double d2 = fr.parse(text, pos01).doubleValue();
if(d2 != d) {
errln("ERROR: Roundtrip failed (via parse()) for " + text);
}
logln(text + " parsed into " + d2);
double d3 = 0;
try {
d3 = fr.parse(text).doubleValue();
}
catch (ParseException e) {
errln("ERROR: parse() failed");
}
if(d3 != d) {
errln("ERROR: Roundtrip failed (via parse()) for " + text);
}
logln(text + " parsed into " + d3);
// ======= Test getters and setters
logln("Testing getters and setters");
final Locale[] locales = NumberFormat.getAvailableLocales();
long count = locales.length;
logln("Got " + count + " locales" );
for(int i = 0; i < count; i++) {
String name;
name = locales[i].getDisplayName();
logln(name);
}
fr.setParseIntegerOnly( def.isParseIntegerOnly() );
if(fr.isParseIntegerOnly() != def.isParseIntegerOnly() ) {
errln("ERROR: setParseIntegerOnly() failed");
}
fr.setGroupingUsed( def.isGroupingUsed() );
if(fr.isGroupingUsed() != def.isGroupingUsed() ) {
errln("ERROR: setGroupingUsed() failed");
}
fr.setMaximumIntegerDigits( def.getMaximumIntegerDigits() );
if(fr.getMaximumIntegerDigits() != def.getMaximumIntegerDigits() ) {
errln("ERROR: setMaximumIntegerDigits() failed");
}
fr.setMinimumIntegerDigits( def.getMinimumIntegerDigits() );
if(fr.getMinimumIntegerDigits() != def.getMinimumIntegerDigits() ) {
errln("ERROR: setMinimumIntegerDigits() failed");
}
fr.setMaximumFractionDigits( def.getMaximumFractionDigits() );
if(fr.getMaximumFractionDigits() != def.getMaximumFractionDigits() ) {
errln("ERROR: setMaximumFractionDigits() failed");
}
fr.setMinimumFractionDigits( def.getMinimumFractionDigits() );
if(fr.getMinimumFractionDigits() != def.getMinimumFractionDigits() ) {
errln("ERROR: setMinimumFractionDigits() failed");
}
// ======= Test getStaticClassID()
// logln("Testing instanceof()");
// try {
// NumberFormat test = new DecimalFormat();
// if (! (test instanceof DecimalFormat)) {
// errln("ERROR: instanceof failed");
// }
// }
// catch (Exception e) {
// errln("ERROR: Couldn't create a DecimalFormat");
// }
}
}

View File

@ -0,0 +1,164 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/dev/test/format/NumberFormatRegressionTest.java,v $
* $Date: 2001/10/19 12:14:05 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : NumberFormatRegressionTest
* Source File: $ICU4CRoot/source/test/intltest/numrgts.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
import java.util.Date;
import java.text.ParseException;
/**
* Performs regression test for MessageFormat
**/
public class NumberFormatRegressionTest extends com.ibm.test.TestFmwk {
public static void main(String[] args) throws Exception{
new NumberFormatRegressionTest().run(args);
}
/**
* alphaWorks upgrade
*/
public void Test4161100() {
NumberFormat nf = NumberFormat.getInstance(Locale.US);
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(1);
double a = -0.09;
String s = nf.format(a);
logln(a + " x " +
((DecimalFormat) nf).toPattern() + " = " + s);
if (!s.equals("-0.1")) {
errln("FAIL");
}
}
/**
* DateFormat should call setIntegerParseOnly(TRUE) on adopted
* NumberFormat objects.
*/
public void TestJ691() {
Locale loc = new Locale("fr", "CH");
// set up the input date string & expected output
String udt = "11.10.2000";
String exp = "11.10.00";
// create a Calendar for this locale
Calendar cal = Calendar.getInstance(loc);
// create a NumberFormat for this locale
NumberFormat nf = NumberFormat.getInstance(loc);
// *** Here's the key: We don't want to have to do THIS:
//nf.setParseIntegerOnly(true);
// create the DateFormat
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, loc);
df.setCalendar(cal);
df.setNumberFormat(nf);
// set parsing to lenient & parse
Date ulocdat = new Date();
df.setLenient(true);
try {
ulocdat = df.parse(udt);
} catch (java.text.ParseException pe) {
errln(pe.getMessage());
}
// format back to a string
String outString = df.format(ulocdat);
if (!outString.equals(exp)) {
errln("FAIL: " + udt + " => " + outString);
}
}
/**
* Test getIntegerInstance();
*/
public void Test4408066() {
NumberFormat nf1 = NumberFormat.getIntegerInstance();
NumberFormat nf2 = NumberFormat.getIntegerInstance(Locale.CHINA);
//test isParseIntegerOnly
if (!nf1.isParseIntegerOnly() || !nf2.isParseIntegerOnly()) {
errln("Failed : Integer Number Format Instance should set setParseIntegerOnly(true)");
}
//Test format
{
double[] data = {
-3.75, -2.5, -1.5,
-1.25, 0, 1.0,
1.25, 1.5, 2.5,
3.75, 10.0, 255.5
};
String[] expected = {
"-4", "-2", "-2",
"-1", "0", "1",
"1", "2", "2",
"4", "10", "256"
};
for (int i = 0; i < data.length; ++i) {
String result = nf1.format(data[i]);
if (!result.equals(expected[i])) {
errln("Failed => Source: " + Double.toString(data[i])
+ ";Formatted : " + result
+ ";but expectted: " + expected[i]);
}
}
}
//Test parse, Parsing should stop at "."
{
String data[] = {
"-3.75", "-2.5", "-1.5",
"-1.25", "0", "1.0",
"1.25", "1.5", "2.5",
"3.75", "10.0", "255.5"
};
long[] expected = {
-3, -2, -1,
-1, 0, 1,
1, 1, 2,
3, 10, 255
};
for (int i = 0; i < data.length; ++i) {
Number n = null;
try {
n = nf1.parse(data[i]);
} catch (ParseException e) {
errln("Failed: " + e.getMessage());
}
if (!(n instanceof Long) || (n instanceof Integer)) {
errln("Failed: Integer Number Format should parse string to Long/Integer");
}
if (n.longValue() != expected[i]) {
errln("Failed=> Source: " + data[i]
+ ";result : " + n.toString()
+ ";expected :" + Long.toString(expected[i]));
}
}
}
}
}

View File

@ -0,0 +1,235 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/dev/test/format/NumberFormatRoundTripTest.java,v $
* $Date: 2001/10/19 12:14:56 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
/**
* Porting From: ICU4C v1.8.1 : format : NumberFormatRoundTripTest
* Source File: $ICU4CRoot/source/test/intltest/nmfmtrt.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
/**
* Performs round-trip tests for NumberFormat
**/
public class NumberFormatRoundTripTest extends com.ibm.test.TestFmwk {
public double MAX_ERROR = 1e-14;
public double max_numeric_error = 0.0;
public double min_numeric_error = 1.0;
public boolean verbose = false;
public boolean STRING_COMPARE = false;
public boolean EXACT_NUMERIC_COMPARE = false;
public boolean DEBUG = false;
public boolean quick = true;
public static void main(String[] args) throws Exception {
new NumberFormatRoundTripTest().run(args);
}
public void TestNumberFormatRoundTrip() {
NumberFormat fmt = null;
logln("Default Locale");
logln("Default Number format");
fmt = NumberFormat.getInstance();
_test(fmt);
logln("Currency Format");
fmt = NumberFormat.getCurrencyInstance();
_test(fmt);
logln("Percent Format");
fmt = NumberFormat.getPercentInstance();
_test(fmt);
int locCount = 0;
final Locale[] loc = NumberFormat.getAvailableLocales();
if(quick) {
if(locCount > 5)
locCount = 5;
logln("Quick mode: only _testing first 5 Locales");
}
for(int i = 0; i < locCount; ++i) {
logln(loc[i].getDisplayName());
fmt = NumberFormat.getInstance(loc[i]);
_test(fmt);
fmt = NumberFormat.getCurrencyInstance(loc[i]);
_test(fmt);
fmt = NumberFormat.getPercentInstance(loc[i]);
_test(fmt);
}
logln("Numeric error " + min_numeric_error + " to " + max_numeric_error);
}
/**
* Return a random value from -range..+range.
*/
public double randomDouble(double range) {
return Math.random() * range;
}
public void _test(NumberFormat fmt) {
_test(fmt, Double.NaN);
_test(fmt, Double.POSITIVE_INFINITY);
_test(fmt, Double.NEGATIVE_INFINITY);
_test(fmt, 500);
_test(fmt, 0);
_test(fmt, -0);
_test(fmt, 0.0);
double negZero = 0.0;
negZero /= -1.0;
_test(fmt, negZero);
_test(fmt, 9223372036854775808.0d);
_test(fmt, -9223372036854775809.0d);
//_test(fmt, 6.936065876100493E74d);
// _test(fmt, 6.212122845281909E48d);
for (int i = 0; i < 10; ++i) {
_test(fmt, randomDouble(1));
_test(fmt, randomDouble(10000));
_test(fmt, Math.floor((randomDouble(10000))));
_test(fmt, randomDouble(1e50));
_test(fmt, randomDouble(1e-50));
_test(fmt, randomDouble(1e100));
_test(fmt, randomDouble(1e75));
_test(fmt, randomDouble(1e308) / ((DecimalFormat) fmt).getMultiplier());
_test(fmt, randomDouble(1e75) / ((DecimalFormat) fmt).getMultiplier());
_test(fmt, randomDouble(1e65) / ((DecimalFormat) fmt).getMultiplier());
_test(fmt, randomDouble(1e-292));
_test(fmt, randomDouble(1e-78));
_test(fmt, randomDouble(1e-323));
_test(fmt, randomDouble(1e-100));
_test(fmt, randomDouble(1e-78));
}
}
public void _test(NumberFormat fmt, double value) {
_test(fmt, new Double(value));
}
public void _test(NumberFormat fmt, long value) {
_test(fmt, new Long(value));
}
public void _test(NumberFormat fmt, Number value) {
logln("test data = " + value);
fmt.setMaximumFractionDigits(999);
String s, s2;
if (value.getClass().getName().equalsIgnoreCase("java.lang.Double"))
s = fmt.format(value.doubleValue());
else
s = fmt.format(value.longValue());
Number n = new Double(0);
boolean show = verbose;
if (DEBUG)
logln(
/*value.getString(temp) +*/ " F> " + s);
try {
n = fmt.parse(s);
} catch (java.text.ParseException e) {
System.out.println(e);
}
if (DEBUG)
logln(s + " P> " /*+ n.getString(temp)*/);
if (value.getClass().getName().equalsIgnoreCase("java.lang.Double"))
s2 = fmt.format(n.doubleValue());
else
s2 = fmt.format(n.longValue());
if (DEBUG)
logln(/*n.getString(temp) +*/ " F> " + s2);
if (STRING_COMPARE) {
if (!s.equals(s2)) {
errln("*** STRING ERROR \"" + s + "\" != \"" + s2 + "\"");
show = true;
}
}
if (EXACT_NUMERIC_COMPARE) {
if (value != n) {
errln("*** NUMERIC ERROR");
show = true;
}
} else {
// Compute proportional error
double error = proportionalError(value, n);
if (error > MAX_ERROR) {
errln("*** NUMERIC ERROR " + error);
show = true;
}
if (error > max_numeric_error)
max_numeric_error = error;
if (error < min_numeric_error)
min_numeric_error = error;
}
if (show)
logln(
/*value.getString(temp) +*/ value.getClass().getName() + " F> " + s + " P> " +
/*n.getString(temp) +*/ n.getClass().getName() + " F> " + s2);
}
public double proportionalError(Number a, Number b) {
double aa,bb;
if(a.getClass().getName().equalsIgnoreCase("java.lang.Double"))
aa = a.doubleValue();
else
aa = a.longValue();
if(a.getClass().getName().equalsIgnoreCase("java.lang.Double"))
bb = b.doubleValue();
else
bb = b.longValue();
double error = aa - bb;
if(aa != 0 && bb != 0)
error /= aa;
return Math.abs(error);
}
}

View File

@ -0,0 +1,696 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/dev/test/format/NumberFormatTest.java,v $
* $Date: 2001/10/19 12:15:50 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : NumberFormatTest
* Source File: $ICU4CRoot/source/test/intltest/numfmtst.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
import java.text.ParsePosition;
import java.text.ParseException;
import java.text.FieldPosition;
public class NumberFormatTest extends com.ibm.test.TestFmwk {
public static void main(String[] args) throws Exception {
new NumberFormatTest().run(args);
}
// Test various patterns
public void TestPatterns() {
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
final String pat[] = { "#.#", "#.", ".#", "#" };
int pat_length = pat.length;
final String newpat[] = { "#0.#", "#0.", "#.0", "#" };
final String num[] = { "0", "0.", ".0", "0" };
for (int i=0; i<pat_length; ++i)
{
DecimalFormat fmt = new DecimalFormat(pat[i], sym);
String newp = fmt.toPattern();
if (!newp.equals(newpat[i]))
errln("FAIL: Pattern " + pat[i] + " should transmute to " + newpat[i] +
"; " + newp + " seen instead");
String s = ((NumberFormat)fmt).format(0);
if (!s.equals(num[i]))
{
errln("FAIL: Pattern " + pat[i] + " should format zero as " + num[i] +
"; " + s + " seen instead");
logln("Min integer digits = " + fmt.getMinimumIntegerDigits());
}
}
}
// Test exponential pattern
public void TestExponential() {
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
final String pat[] = { "0.####E0", "00.000E00", "##0.######E000", "0.###E0;[0.###E0]" };
int pat_length = pat.length;
double val[] = { 0.01234, 123456789, 1.23e300, -3.141592653e-271 };
int val_length = val.length;
final String valFormat[] = {
// 0.####E0
"1.234E-2", "1.2346E8", "1.23E300", "-3.1416E-271",
// 00.000E00
"12.340E-03", "12.346E07", "12.300E299", "-31.416E-272",
// ##0.######E000
"12.34E-003", "123.4568E006", "1.23E300", "-314.1593E-273",
// 0.###E0;[0.###E0]
"1.234E-2", "1.235E8", "1.23E300", "[3.142E-271]" };
double valParse[] =
{
0.01234, 123460000, 1.23E300, -3.1416E-271,
0.01234, 123460000, 1.23E300, -3.1416E-271,
0.01234, 123456800, 1.23E300, -3.141593E-271,
0.01234, 123500000, 1.23E300, -3.142E-271,
};
int lval[] = { 0, -1, 1, 123456789 };
int lval_length = lval.length;
final String lvalFormat[] = {
// 0.####E0
"0E0", "-1E0", "1E0", "1.2346E8",
// 00.000E00
"00.000E00", "-10.000E-01", "10.000E-01", "12.346E07",
// ##0.######E000
"0E000", "-1E000", "1E000", "123.4568E006",
// 0.###E0;[0.###E0]
"0E0", "[1E0]", "1E0", "1.235E8" };
int lvalParse[] =
{
0, -1, 1, 123460000,
0, -1, 1, 123460000,
0, -1, 1, 123456800,
0, -1, 1, 123500000,
};
int ival = 0, ilval = 0;
for (int p = 0; p < pat_length; ++p) {
DecimalFormat fmt = new DecimalFormat(pat[p], sym);
String pattern;
logln("Pattern \"" + pat[p] + "\" -toPattern-> \"" + fmt.toPattern() + "\"");
int v;
for (v = 0; v < val_length; ++v) {
String s;
s = ((NumberFormat) fmt).format(val[v]);
logln(" " + val[v] + " -format-> " + s);
if (!s.equals(valFormat[v + ival]))
errln("FAIL: Expected " + valFormat[v + ival]);
ParsePosition pos = new ParsePosition(0);
double a = fmt.parse(s, pos).doubleValue();
if (pos.getIndex() == s.length()) {
logln(" -parse-> " + Double.toString(a));
// Use epsilon comparison as necessary
} else
errln("FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + a);
}
for (v = 0; v < lval_length; ++v) {
String s;
s = ((NumberFormat) fmt).format(lval[v]);
logln(" " + lval[v] + "L -format-> " + s);
if (!s.equals(lvalFormat[v + ilval]))
errln("ERROR: Expected " + lvalFormat[v + ilval] + " Got: " + s);
ParsePosition pos = new ParsePosition(0);
long a = 0;
Number A = fmt.parse(s, pos);
if (A != null) {
a = A.longValue();
if (pos.getIndex() == s.length()) {
logln(" -parse-> " + a);
if (a != lvalParse[v + ilval])
errln("FAIL: Expected " + lvalParse[v + ilval]);
} else
errln("FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + Long.toString(a));
} else {
errln("Fail to parse the string: " + s);
}
}
ival += val_length;
ilval += lval_length;
}
}
// Test the handling of quotes
public void TestQuotes() {
StringBuffer pat;
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
pat = new StringBuffer("a'fo''o'b#");
DecimalFormat fmt = new DecimalFormat(pat.toString(), sym);
String s = ((NumberFormat)fmt).format(123);
logln("Pattern \"" + pat + "\"");
logln(" Format 123 . " + s);
if (!s.equals("afo'ob123"))
errln("FAIL: Expected afo'ob123");
s ="";
pat = new StringBuffer("a''b#");
fmt = new DecimalFormat(pat.toString(), sym);
s = ((NumberFormat)fmt).format(123);
logln("Pattern \"" + pat + "\"");
logln(" Format 123 . " + s);
if (!s.equals("a'b123"))
errln("FAIL: Expected a'b123");
}
/**
* Test the handling of the currency symbol in patterns.
**/
public void TestCurrencySign() {
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
StringBuffer pat = new StringBuffer("");
char currency = 0x00A4;
// "\xA4#,##0.00;-\xA4#,##0.00"
pat.append(currency).append("#,##0.00;-").append(currency).append("#,##0.00");
DecimalFormat fmt = new DecimalFormat(pat.toString(), sym);
String s = ((NumberFormat) fmt).format(1234.56);
pat = new StringBuffer("");
logln("Pattern \"" + fmt.toPattern() + "\"");
logln(" Format " + 1234.56 + " . " + s);
if (!s.equals("$1,234.56"))
errln("FAIL: Expected $1,234.56");
s = "";
s = ((NumberFormat) fmt).format(-1234.56);
logln(" Format " + Double.toString(-1234.56) + " . " + s);
if (!s.equals("-$1,234.56"))
errln("FAIL: Expected -$1,234.56");
pat = new StringBuffer("");
// "\xA4\xA4 #,##0.00;\xA4\xA4 -#,##0.00"
pat.append(currency).append(currency).append(" #,##0.00;").append(currency).append(currency).append(" -#,##0.00");
fmt = new DecimalFormat(pat.toString(), sym);
s = "";
s = ((NumberFormat) fmt).format(1234.56);
logln("Pattern \"" + fmt.toPattern() + "\"");
logln(" Format " + Double.toString(1234.56) + " . " + s);
if (!s.equals("USD 1,234.56"))
errln("FAIL: Expected USD 1,234.56");
s = "";
s = ((NumberFormat) fmt).format(-1234.56);
logln(" Format " + Double.toString(-1234.56) + " . " + s);
if (!s.equals("USD -1,234.56"))
errln("FAIL: Expected USD -1,234.56");
}
/**
* Test localized currency patterns.
*/
public void TestCurrency() {
NumberFormat currencyFmt =
NumberFormat.getCurrencyInstance(Locale.CANADA_FRENCH);
String s;
s = currencyFmt.format(1.50);
logln("Un pauvre ici a..........." + s);
if (!s.equals("1,50 $"))
errln("FAIL: Expected 1,50 $");
s = "";
currencyFmt = NumberFormat.getCurrencyInstance(Locale.GERMANY);
s = currencyFmt.format(1.50);
logln("Un pauvre en Allemagne a.." + s);
if (!s.equals("1,50 DM"))
errln("FAIL: Expected 1,50 DM");
s = "";
currencyFmt = NumberFormat.getCurrencyInstance(Locale.FRANCE);
s = currencyFmt.format(1.50);
logln("Un pauvre en France a....." + s);
if (!s.equals("1,50 F"))
errln("FAIL: Expected 1,50 F");
}
/**
* Do rudimentary testing of parsing.
*/
public void TestParse() {
String arg = "0.0";
DecimalFormat format = new DecimalFormat("00");
double aNumber = 0l;
try {
aNumber = format.parse(arg).doubleValue();
} catch (java.text.ParseException e) {
System.out.println(e);
}
logln("parse(" + arg + ") = " + aNumber);
}
/**
* Test proper rounding by the format method.
*/
public void TestRounding487() {
NumberFormat nf = NumberFormat.getInstance();
roundingTest(nf, 0.00159999, 4, "0.0016");
roundingTest(nf, 0.00995, 4, "0.01");
roundingTest(nf, 12.3995, 3, "12.4");
roundingTest(nf, 12.4999, 0, "12");
roundingTest(nf, - 19.5, 0, "-20");
}
/**
* Test the functioning of the secondary grouping value.
*/
public void TestSecondaryGrouping() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
DecimalFormat f = new DecimalFormat("#,##,###", US);
expect(f, 123456789L, "12,34,56,789");
expectPat(f, "#,##,###");
f.applyPattern("#,###");
f.setSecondaryGroupingSize(4);
expect(f, 123456789L, "12,3456,789");
expectPat(f, "#,####,###");
NumberFormat g = NumberFormat.getInstance(new Locale("hi", "IN"));
String out = "";
long l = 1876543210L;
out = g.format(l);
// expect "1,87,65,43,210", but with Hindi digits
// 01234567890123
boolean ok = true;
if (out.length() != 14) {
ok = false;
} else {
for (int i = 0; i < out.length(); ++i) {
boolean expectGroup = false;
switch (i) {
case 1 :
case 4 :
case 7 :
case 10 :
expectGroup = true;
break;
}
// Later -- fix this to get the actual grouping
// character from the resource bundle.
boolean isGroup = (out.charAt(i) == 0x002C);
if (isGroup != expectGroup) {
ok = false;
break;
}
}
}
if (!ok) {
errln("FAIL Expected "+ l + " x hi_IN . \"1,87,65,43,210\" (with Hindi digits), got \""
+ out + "\"");
} else {
logln("Ok " + l + " x hi_IN . \"" + out + "\"");
}
}
public void roundingTest(NumberFormat nf, double x, int maxFractionDigits, final String expected) {
nf.setMaximumFractionDigits(maxFractionDigits);
String out = nf.format(x);
logln(x + " formats with " + maxFractionDigits + " fractional digits to " + out);
if (!out.equals(expected))
errln("FAIL: Expected " + expected);
}
/**
* Upgrade to alphaWorks
*/
public void expect(NumberFormat fmt, String str, int n) {
Long num = new Long(0);
try {
num = (Long)fmt.parse(str);
} catch (java.text.ParseException e) {
}
String pat = ((DecimalFormat)fmt).toPattern();
if (num.longValue() == n) {
logln("Ok \"" + str + "\" x " +
pat + " = " +
num.toString());
} else {
errln("FAIL \"" + str + "\" x " +
pat + " = " +
num.toString() + ", expected " + n + "L");
}
}
/**
* Upgrade to alphaWorks
*/
public void expect(NumberFormat fmt, final double n, final String exp) {
StringBuffer saw = new StringBuffer("");
FieldPosition pos = new FieldPosition(0);
saw = fmt.format(n, saw, pos);
String pat = ((DecimalFormat)fmt).toPattern();
if (saw.toString().equals(exp)) {
logln("Ok " + Double.toString(n) + " x " +
pat + " = \"" +
saw + "\"");
} else {
errln("FAIL " + Double.toString(n) + " x " +
pat + " = \"" +
saw + "\", expected \"" + exp + "\"");
}
}
/**
* Upgrade to alphaWorks
*/
public void TestExponent() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
DecimalFormat fmt1 = new DecimalFormat("0.###E0", US);
DecimalFormat fmt2 = new DecimalFormat("0.###E+0", US);
int n = 1234;
expect(fmt1, n, "1.234E3");
expect(fmt2, n, "1.234E+3");
expect(fmt1, "1.234E3", n);
expect(fmt1, "1.234E+3", n); // Either format should parse "E+3"
expect(fmt2, "1.234E+3", n);
}
/**
* Upgrade to alphaWorks
*/
public void TestScientific() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
// Test pattern round-trip
final String PAT[] = { "#E0", "0.####E0", "00.000E00", "##0.####E000", "0.###E0;[0.###E0]" };
int PAT_length = PAT.length;
int DIGITS[] = {
// min int, max int, min frac, max frac
0, 1, 0, 0, // "#E0"
1, 1, 0, 4, // "0.####E0"
2, 2, 3, 3, // "00.000E00"
1, 3, 0, 4, // "##0.####E000"
1, 1, 0, 3, // "0.###E0;[0.###E0]"
};
for (int i = 0; i < PAT_length; ++i) {
String pat = PAT[i];
DecimalFormat df = new DecimalFormat(pat, US);
String pat2 = df.toPattern();
if (pat.equals(pat2)) {
logln("Ok Pattern rt \"" + pat + "\" . \"" + pat2 + "\"");
} else {
errln("FAIL Pattern rt \"" + pat + "\" . \"" + pat2 + "\"");
}
// Make sure digit counts match what we expect
if (df.getMinimumIntegerDigits() != DIGITS[4 * i]
|| df.getMaximumIntegerDigits() != DIGITS[4 * i + 1]
|| df.getMinimumFractionDigits() != DIGITS[4 * i + 2]
|| df.getMaximumFractionDigits() != DIGITS[4 * i + 3]) {
errln("FAIL \""+ pat+ "\" min/max int; min/max frac = "
+ df.getMinimumIntegerDigits() + "/"
+ df.getMaximumIntegerDigits() + ";"
+ df.getMinimumFractionDigits() + "/"
+ df.getMaximumFractionDigits() + ", expect "
+ DIGITS[4 * i] + "/"
+ DIGITS[4 * i + 1] + ";"
+ DIGITS[4 * i + 2] + "/"
+ DIGITS[4 * i + 3]);
}
}
expect(new DecimalFormat("#E0", US), 12345.0, "1.2345E4");
expect(new DecimalFormat("0E0", US), 12345.0, "1E4");
// pattern of NumberFormat.getScientificInstance(Locale.US) = "0.######E0" not "#E0"
// so result = 1.234568E4 not 1.2345678901E4
//when the pattern problem is finalized, delete comment mark'//'
//of the following code
expect(NumberFormat.getScientificInstance(Locale.US), 12345.678901, "1.2345678901E4");
expect(new DecimalFormat("##0.###E0", US), 12345.0, "12.34E3");
expect(new DecimalFormat("##0.###E0", US), 12345.00001, "12.35E3");
expect(new DecimalFormat("##0.####E0", US), 12345, "12.345E3");
// pattern of NumberFormat.getScientificInstance(Locale.US) = "0.######E0" not "#E0"
// so result = 1.234568E4 not 1.2345678901E4
expect(NumberFormat.getScientificInstance(Locale.FRANCE), 12345.678901, "1,2345678901E4");
expect(new DecimalFormat("##0.####E0", US), 789.12345e-9, "789.12E-9");
expect(new DecimalFormat("##0.####E0", US), 780.e-9, "780E-9");
expect(new DecimalFormat(".###E0", US), 45678.0, ".457E5");
expect(new DecimalFormat(".###E0", US), 0, ".0E0");
/*
expect(new DecimalFormat[] { new DecimalFormat("#E0", US),
new DecimalFormat("##E0", US),
new DecimalFormat("####E0", US),
new DecimalFormat("0E0", US),
new DecimalFormat("00E0", US),
new DecimalFormat("000E0", US),
},
new Long(45678000),
new String[] { "4.5678E7",
"45.678E6",
"4567.8E4",
"5E7",
"46E6",
"457E5",
}
);
!
! Unroll this test into individual tests below...
!
*/
expect(new DecimalFormat("#E0", US), 45678000, "4.5678E7");
expect(new DecimalFormat("##E0", US), 45678000, "45.678E6");
expect(new DecimalFormat("####E0", US), 45678000, "4567.8E4");
expect(new DecimalFormat("0E0", US), 45678000, "5E7");
expect(new DecimalFormat("00E0", US), 45678000, "46E6");
expect(new DecimalFormat("000E0", US), 45678000, "457E5");
/*
expect(new DecimalFormat("###E0", US, status),
new Object[] { new Double(0.0000123), "12.3E-6",
new Double(0.000123), "123E-6",
new Double(0.00123), "1.23E-3",
new Double(0.0123), "12.3E-3",
new Double(0.123), "123E-3",
new Double(1.23), "1.23E0",
new Double(12.3), "12.3E0",
new Double(123), "123E0",
new Double(1230), "1.23E3",
});
!
! Unroll this test into individual tests below...
!
*/
expect(new DecimalFormat("###E0", US), 0.0000123, "12.3E-6");
expect(new DecimalFormat("###E0", US), 0.000123, "123E-6");
expect(new DecimalFormat("###E0", US), 0.00123, "1.23E-3");
expect(new DecimalFormat("###E0", US), 0.0123, "12.3E-3");
expect(new DecimalFormat("###E0", US), 0.123, "123E-3");
expect(new DecimalFormat("###E0", US), 1.23, "1.23E0");
expect(new DecimalFormat("###E0", US), 12.3, "12.3E0");
expect(new DecimalFormat("###E0", US), 123.0, "123E0");
expect(new DecimalFormat("###E0", US), 1230.0, "1.23E3");
/*
expect(new DecimalFormat("0.#E+00", US, status),
new Object[] { new Double(0.00012), "1.2E-04",
new Long(12000), "1.2E+04",
});
!
! Unroll this test into individual tests below...
!
*/
expect(new DecimalFormat("0.#E+00", US), 0.00012, "1.2E-04");
expect(new DecimalFormat("0.#E+00", US), 12000, "1.2E+04");
}
/**
* Upgrade to alphaWorks
*/
public void TestPad() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
expect(new DecimalFormat("*^##.##", US), 0, "^^^^0");
expect(new DecimalFormat("*^##.##", US), -1.3, "^-1.3");
expect(
new DecimalFormat("##0.0####E0*_ g-m/s^2", US),
0,
"0.0E0______ g-m/s^2");
expect(
new DecimalFormat("##0.0####E0*_ g-m/s^2", US),
1.0 / 3,
"333.333E-3_ g-m/s^2");
expect(new DecimalFormat("##0.0####*_ g-m/s^2", US), 0, "0.0______ g-m/s^2");
expect(
new DecimalFormat("##0.0####*_ g-m/s^2", US),
1.0 / 3,
"0.33333__ g-m/s^2");
// Test padding before a sign
final String formatStr = "*x#,###,###,##0.0#;*x(###,###,##0.0#)";
expect(new DecimalFormat(formatStr, US), -10, "xxxxxxxxxx(10.0)");
expect(new DecimalFormat(formatStr, US), -1000, "xxxxxxx(1,000.0)");
expect(new DecimalFormat(formatStr, US), -1000000, "xxx(1,000,000.0)");
expect(new DecimalFormat(formatStr, US), -100.37, "xxxxxxxx(100.37)");
expect(new DecimalFormat(formatStr, US), -10456.37, "xxxxx(10,456.37)");
expect(new DecimalFormat(formatStr, US), -1120456.37, "xx(1,120,456.37)");
expect(new DecimalFormat(formatStr, US), -112045600.37, "(112,045,600.37)");
expect(new DecimalFormat(formatStr, US), -1252045600.37, "(1,252,045,600.37)");
expect(new DecimalFormat(formatStr, US), 10, "xxxxxxxxxxxx10.0");
expect(new DecimalFormat(formatStr, US), 1000, "xxxxxxxxx1,000.0");
expect(new DecimalFormat(formatStr, US), 1000000, "xxxxx1,000,000.0");
expect(new DecimalFormat(formatStr, US), 100.37, "xxxxxxxxxx100.37");
expect(new DecimalFormat(formatStr, US), 10456.37, "xxxxxxx10,456.37");
expect(new DecimalFormat(formatStr, US), 1120456.37, "xxxx1,120,456.37");
expect(new DecimalFormat(formatStr, US), 112045600.37, "xx112,045,600.37");
expect(new DecimalFormat(formatStr, US), 10252045600.37, "10,252,045,600.37");
// Test padding between a sign and a number
final String formatStr2 = "#,###,###,##0.0#*x;(###,###,##0.0#*x)";
expect(new DecimalFormat(formatStr2, US), -10, "(10.0xxxxxxxxxx)");
expect(new DecimalFormat(formatStr2, US), -1000, "(1,000.0xxxxxxx)");
expect(new DecimalFormat(formatStr2, US), -1000000, "(1,000,000.0xxx)");
expect(new DecimalFormat(formatStr2, US), -100.37, "(100.37xxxxxxxx)");
expect(new DecimalFormat(formatStr2, US), -10456.37, "(10,456.37xxxxx)");
expect(new DecimalFormat(formatStr2, US), -1120456.37, "(1,120,456.37xx)");
expect(new DecimalFormat(formatStr2, US), -112045600.37, "(112,045,600.37)");
expect(new DecimalFormat(formatStr2, US), -1252045600.37, "(1,252,045,600.37)");
expect(new DecimalFormat(formatStr2, US), 10, "10.0xxxxxxxxxxxx");
expect(new DecimalFormat(formatStr2, US), 1000, "1,000.0xxxxxxxxx");
expect(new DecimalFormat(formatStr2, US), 1000000, "1,000,000.0xxxxx");
expect(new DecimalFormat(formatStr2, US), 100.37, "100.37xxxxxxxxxx");
expect(new DecimalFormat(formatStr2, US), 10456.37, "10,456.37xxxxxxx");
expect(new DecimalFormat(formatStr2, US), 1120456.37, "1,120,456.37xxxx");
expect(new DecimalFormat(formatStr2, US), 112045600.37, "112,045,600.37xx");
expect(new DecimalFormat(formatStr2, US), 10252045600.37, "10,252,045,600.37");
//testing the setPadCharacter(UnicodeString) and getPadCharacterString()
DecimalFormat fmt = new DecimalFormat("#", US);
char padString = 'P';
fmt.setPadCharacter(padString);
expectPad(fmt, "*P##.##", DecimalFormat.PAD_BEFORE_PREFIX, 5, padString);
fmt.setPadCharacter('^');
expectPad(fmt, "*^#", DecimalFormat.PAD_BEFORE_PREFIX, 1, '^');
//commented untill implementation is complete
/* fmt.setPadCharacter((UnicodeString)"^^^");
expectPad(fmt, "*^^^#", DecimalFormat.kPadBeforePrefix, 3, (UnicodeString)"^^^");
padString.remove();
padString.append((UChar)0x0061);
padString.append((UChar)0x0302);
fmt.setPadCharacter(padString);
UChar patternChars[]={0x002a, 0x0061, 0x0302, 0x0061, 0x0302, 0x0023, 0x0000};
UnicodeString pattern(patternChars);
expectPad(fmt, pattern , DecimalFormat.kPadBeforePrefix, 4, padString);
*/
}
/**
* Upgrade to alphaWorks
*/
public void TestPatterns2() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
DecimalFormat fmt = new DecimalFormat("#", US);
char hat = 0x005E; /*^*/
expectPad(fmt, "*^#", DecimalFormat.PAD_BEFORE_PREFIX, 1, hat);
expectPad(fmt, "$*^#", DecimalFormat.PAD_AFTER_PREFIX, 2, hat);
expectPad(fmt, "#*^", DecimalFormat.PAD_BEFORE_SUFFIX, 1, hat);
expectPad(fmt, "#$*^", DecimalFormat.PAD_AFTER_SUFFIX, 2, hat);
expectPad(fmt, "$*^$#", -1);
expectPad(fmt, "#$*^$", -1);
expectPad(fmt, "'pre'#,##0*x'post'", DecimalFormat.PAD_BEFORE_SUFFIX, 12, (char) 0x0078 /*x*/);
expectPad(fmt, "''#0*x", DecimalFormat.PAD_BEFORE_SUFFIX, 3, (char) 0x0078 /*x*/);
expectPad(fmt, "'I''ll'*a###.##", DecimalFormat.PAD_AFTER_PREFIX, 10, (char) 0x0061 /*a*/);
fmt.applyPattern("AA#,##0.00ZZ");
fmt.setPadCharacter(hat);
fmt.setFormatWidth(10);
fmt.setPadPosition(DecimalFormat.PAD_BEFORE_PREFIX);
expectPat(fmt, "*^AA#,##0.00ZZ");
fmt.setPadPosition(DecimalFormat.PAD_BEFORE_SUFFIX);
expectPat(fmt, "AA#,##0.00*^ZZ");
fmt.setPadPosition(DecimalFormat.PAD_AFTER_SUFFIX);
expectPat(fmt, "AA#,##0.00ZZ*^");
// 12 3456789012
String exp = "AA*^#,##0.00ZZ";
fmt.setFormatWidth(12);
fmt.setPadPosition(DecimalFormat.PAD_AFTER_PREFIX);
expectPat(fmt, exp);
fmt.setFormatWidth(13);
// 12 34567890123
expectPat(fmt, "AA*^##,##0.00ZZ");
fmt.setFormatWidth(14);
// 12 345678901234
expectPat(fmt, "AA*^###,##0.00ZZ");
fmt.setFormatWidth(15);
// 12 3456789012345
expectPat(fmt, "AA*^####,##0.00ZZ"); // This is the interesting case
fmt.setFormatWidth(16);
// 12 34567890123456
expectPat(fmt, "AA*^#,###,##0.00ZZ");
}
public void expectPad(DecimalFormat fmt, String pat, int pos) {
expectPad(fmt, pat, pos, 0, (char)0);
}
public void expectPad(DecimalFormat fmt, final String pat, int pos, int width, final char pad) {
int apos = 0, awidth = 0;
char apadStr;
try {
fmt.applyPattern(pat);
apos = fmt.getPadPosition();
awidth = fmt.getFormatWidth();
apadStr = fmt.getPadCharacter();
} catch (Exception e) {
apos = -1;
awidth = width;
apadStr = pad;
}
if (apos == pos && awidth == width && apadStr == pad) {
logln("Ok \"" + pat + "\" pos="
+ apos + ((pos == -1) ? "" : " width=" + awidth + " pad=" + apadStr));
} else {
errln("FAIL \"" + pat + "\" pos=" + apos + " width="
+ awidth + " pad=" + apadStr + ", expected "
+ pos + " " + width + " " + pad);
}
}
public void expectPat(DecimalFormat fmt, final String exp) {
String pat = fmt.toPattern();
if (pat.equals(exp)) {
logln("Ok \"" + pat + "\"");
} else {
errln("FAIL \"" + pat + "\", expected \"" + exp + "\"");
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,236 @@
/*****************************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestDecimalFormatAPI.java,v $
* $Date: 2001/10/19 12:09:26 $
* $Revision: 1.1 $
*
*****************************************************************************************
**/
/**
* Port From: JDK 1.4b1 : java.text.Format.IntlTestDecimalFormatAPI
* Source File: java/text/format/IntlTestDecimalFormatAPI.java
**/
/*
@test 1.4 98/03/06
@summary test International Decimal Format API
*/
/*
(C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
(C) Copyright IBM Corp. 1996, 1997, 2001 - All Rights Reserved
The original version of this source code and documentation is copyrighted and
owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These materials are
provided under terms of a License Agreement between Taligent and Sun. This
technology is protected by multiple US and International patents. This notice and
attribution to Taligent may not be removed.
Taligent is a registered trademark of Taligent, Inc.
*/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
import java.text.ParsePosition;
import java.text.Format;
import java.text.FieldPosition;
public class IntlTestDecimalFormatAPI extends com.ibm.test.TestFmwk
{
public static void main(String[] args) throws Exception {
new IntlTestDecimalFormatAPI().run(args);
}
// This test checks various generic API methods in DecimalFormat to achieve 100% API coverage.
public void TestAPI()
{
logln("DecimalFormat API test---"); logln("");
Locale.setDefault(Locale.ENGLISH);
// ======= Test constructors
logln("Testing DecimalFormat constructors");
DecimalFormat def = new DecimalFormat();
final String pattern = new String("#,##0.# FF");
DecimalFormat pat = null;
try {
pat = new DecimalFormat(pattern);
}
catch (IllegalArgumentException e) {
errln("ERROR: Could not create DecimalFormat (pattern)");
}
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.FRENCH);
DecimalFormat cust1 = new DecimalFormat(pattern, symbols);
// ======= Test clone(), assignment, and equality
logln("Testing clone() and equality operators");
Format clone = (Format) def.clone();
if( ! def.equals(clone)) {
errln("ERROR: Clone() failed");
}
// ======= Test various format() methods
logln("Testing various format() methods");
// final double d = -10456.0037; // this appears as -10456.003700000001 on NT
// final double d = -1.04560037e-4; // this appears as -1.0456003700000002E-4 on NT
final double d = -10456.00370000000000; // this works!
final long l = 100000000;
logln("" + d + " is the double value");
StringBuffer res1 = new StringBuffer();
StringBuffer res2 = new StringBuffer();
StringBuffer res3 = new StringBuffer();
StringBuffer res4 = new StringBuffer();
FieldPosition pos1 = new FieldPosition(0);
FieldPosition pos2 = new FieldPosition(0);
FieldPosition pos3 = new FieldPosition(0);
FieldPosition pos4 = new FieldPosition(0);
res1 = def.format(d, res1, pos1);
logln("" + d + " formatted to " + res1);
res2 = pat.format(l, res2, pos2);
logln("" + l + " formatted to " + res2);
res3 = cust1.format(d, res3, pos3);
logln("" + d + " formatted to " + res3);
res4 = cust1.format(l, res4, pos4);
logln("" + l + " formatted to " + res4);
// ======= Test parse()
logln("Testing parse()");
String text = new String("-10,456.0037");
ParsePosition pos = new ParsePosition(0);
String patt = new String("#,##0.#");
pat.applyPattern(patt);
double d2 = pat.parse(text, pos).doubleValue();
if(d2 != d) {
errln("ERROR: Roundtrip failed (via parse(" + d2 + " != " + d + ")) for " + text);
}
logln(text + " parsed into " + (long) d2);
// ======= Test getters and setters
logln("Testing getters and setters");
final DecimalFormatSymbols syms = pat.getDecimalFormatSymbols();
def.setDecimalFormatSymbols(syms);
if( ! pat.getDecimalFormatSymbols().equals(def.getDecimalFormatSymbols())) {
errln("ERROR: set DecimalFormatSymbols() failed");
}
String posPrefix;
pat.setPositivePrefix("+");
posPrefix = pat.getPositivePrefix();
logln("Positive prefix (should be +): " + posPrefix);
if(posPrefix != "+") {
errln("ERROR: setPositivePrefix() failed");
}
String negPrefix;
pat.setNegativePrefix("-");
negPrefix = pat.getNegativePrefix();
logln("Negative prefix (should be -): " + negPrefix);
if(negPrefix != "-") {
errln("ERROR: setNegativePrefix() failed");
}
String posSuffix;
pat.setPositiveSuffix("_");
posSuffix = pat.getPositiveSuffix();
logln("Positive suffix (should be _): " + posSuffix);
if(posSuffix != "_") {
errln("ERROR: setPositiveSuffix() failed");
}
String negSuffix;
pat.setNegativeSuffix("~");
negSuffix = pat.getNegativeSuffix();
logln("Negative suffix (should be ~): " + negSuffix);
if(negSuffix != "~") {
errln("ERROR: setNegativeSuffix() failed");
}
long multiplier = 0;
pat.setMultiplier(8);
multiplier = pat.getMultiplier();
logln("Multiplier (should be 8): " + multiplier);
if(multiplier != 8) {
errln("ERROR: setMultiplier() failed");
}
int groupingSize = 0;
pat.setGroupingSize(2);
groupingSize = pat.getGroupingSize();
logln("Grouping size (should be 2): " + (long) groupingSize);
if(groupingSize != 2) {
errln("ERROR: setGroupingSize() failed");
}
pat.setDecimalSeparatorAlwaysShown(true);
boolean tf = pat.isDecimalSeparatorAlwaysShown();
logln("DecimalSeparatorIsAlwaysShown (should be true) is " + (tf ? "true" : "false"));
if(tf != true) {
errln("ERROR: setDecimalSeparatorAlwaysShown() failed");
}
String funkyPat;
funkyPat = pat.toPattern();
logln("Pattern is " + funkyPat);
String locPat;
locPat = pat.toLocalizedPattern();
logln("Localized pattern is " + locPat);
// ======= Test applyPattern()
logln("Testing applyPattern()");
String p1 = new String("#,##0.0#;(#,##0.0#)");
logln("Applying pattern " + p1);
pat.applyPattern(p1);
String s2;
s2 = pat.toPattern();
logln("Extracted pattern is " + s2);
if( ! s2.equals(p1) ) {
errln("ERROR: toPattern() result did not match pattern applied");
}
String p2 = new String("#,##0.0# FF;(#,##0.0# FF)");
logln("Applying pattern " + p2);
pat.applyLocalizedPattern(p2);
String s3;
s3 = pat.toLocalizedPattern();
logln("Extracted pattern is " + s3);
if( ! s3.equals(p2) ) {
errln("ERROR: toLocalizedPattern() result did not match pattern applied");
}
// ======= Test getStaticClassID()
// logln("Testing instanceof()");
// try {
// NumberFormat test = new DecimalFormat();
// if (! (test instanceof DecimalFormat)) {
// errln("ERROR: instanceof failed");
// }
// }
// catch (Exception e) {
// errln("ERROR: Couldn't create a DecimalFormat");
// }
}
}

View File

@ -0,0 +1,287 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestDecimalFormatAPIC.java,v $
* $Date: 2001/10/19 12:10:26 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : IntlTestDecimalFormatAPI
* Source File: $ICU4CRoot/source/test/intltest/dcfmapts.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.util.*;
import java.util.Locale;
import java.text.ParsePosition;
import java.text.Format;
import com.ibm.text.*;
import java.text.FieldPosition;
// This is an API test, not a unit test. It doesn't test very many cases, and doesn't
// try to test the full functionality. It just calls each function in the class and
// verifies that it works on a basic level.
public class IntlTestDecimalFormatAPIC extends com.ibm.test.TestFmwk {
public static void main(String[] args) throws Exception {
new IntlTestDecimalFormatAPIC().run(args);
}
// This test checks various generic API methods in DecimalFormat to achieve 100% API coverage.
public void TestAPI() {
logln("DecimalFormat API test---");
logln("");
Locale.setDefault(Locale.ENGLISH);
// ======= Test constructors
logln("Testing DecimalFormat constructors");
DecimalFormat def = new DecimalFormat();
final String pattern = new String("#,##0.# FF");
DecimalFormat pat = null;
try {
pat = new DecimalFormat(pattern);
} catch (IllegalArgumentException e) {
errln("ERROR: Could not create DecimalFormat (pattern)");
}
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.FRENCH);
DecimalFormat cust1 = new DecimalFormat(pattern, symbols);
// ======= Test clone(), assignment, and equality
logln("Testing clone() and equality operators");
Format clone = (Format) def.clone();
if (!def.equals(clone)) {
errln("ERROR: Clone() failed");
}
// ======= Test various format() methods
logln("Testing various format() methods");
// final double d = -10456.0037; // this appears as -10456.003700000001 on NT
// final double d = -1.04560037e-4; // this appears as -1.0456003700000002E-4 on NT
final double d = -10456.00370000000000; // this works!
final long l = 100000000;
logln("" + Double.toString(d) + " is the double value");
StringBuffer res1 = new StringBuffer();
StringBuffer res2 = new StringBuffer();
StringBuffer res3 = new StringBuffer();
StringBuffer res4 = new StringBuffer();
FieldPosition pos1 = new FieldPosition(0);
FieldPosition pos2 = new FieldPosition(0);
FieldPosition pos3 = new FieldPosition(0);
FieldPosition pos4 = new FieldPosition(0);
res1 = def.format(d, res1, pos1);
logln("" + Double.toString(d) + " formatted to " + res1);
res2 = pat.format(l, res2, pos2);
logln("" + l + " formatted to " + res2);
res3 = cust1.format(d, res3, pos3);
logln("" + Double.toString(d) + " formatted to " + res3);
res4 = cust1.format(l, res4, pos4);
logln("" + l + " formatted to " + res4);
// ======= Test parse()
logln("Testing parse()");
String text = new String("-10,456.0037");
ParsePosition pos = new ParsePosition(0);
String patt = new String("#,##0.#");
pat.applyPattern(patt);
double d2 = pat.parse(text, pos).doubleValue();
if (d2 != d) {
errln(
"ERROR: Roundtrip failed (via parse(" + Double.toString(d2) + " != " + Double.toString(d) + ")) for " + text);
}
logln(text + " parsed into " + (long) d2);
// ======= Test getters and setters
logln("Testing getters and setters");
final DecimalFormatSymbols syms = pat.getDecimalFormatSymbols();
def.setDecimalFormatSymbols(syms);
if (!pat.getDecimalFormatSymbols().equals(def.getDecimalFormatSymbols())) {
errln("ERROR: set DecimalFormatSymbols() failed");
}
String posPrefix;
pat.setPositivePrefix("+");
posPrefix = pat.getPositivePrefix();
logln("Positive prefix (should be +): " + posPrefix);
if (posPrefix != "+") {
errln("ERROR: setPositivePrefix() failed");
}
String negPrefix;
pat.setNegativePrefix("-");
negPrefix = pat.getNegativePrefix();
logln("Negative prefix (should be -): " + negPrefix);
if (negPrefix != "-") {
errln("ERROR: setNegativePrefix() failed");
}
String posSuffix;
pat.setPositiveSuffix("_");
posSuffix = pat.getPositiveSuffix();
logln("Positive suffix (should be _): " + posSuffix);
if (posSuffix != "_") {
errln("ERROR: setPositiveSuffix() failed");
}
String negSuffix;
pat.setNegativeSuffix("~");
negSuffix = pat.getNegativeSuffix();
logln("Negative suffix (should be ~): " + negSuffix);
if (negSuffix != "~") {
errln("ERROR: setNegativeSuffix() failed");
}
long multiplier = 0;
pat.setMultiplier(8);
multiplier = pat.getMultiplier();
logln("Multiplier (should be 8): " + multiplier);
if (multiplier != 8) {
errln("ERROR: setMultiplier() failed");
}
int groupingSize = 0;
pat.setGroupingSize(2);
groupingSize = pat.getGroupingSize();
logln("Grouping size (should be 2): " + (long) groupingSize);
if (groupingSize != 2) {
errln("ERROR: setGroupingSize() failed");
}
pat.setDecimalSeparatorAlwaysShown(true);
boolean tf = pat.isDecimalSeparatorAlwaysShown();
logln(
"DecimalSeparatorIsAlwaysShown (should be true) is " + (tf ? "true" : "false"));
if (tf != true) {
errln("ERROR: setDecimalSeparatorAlwaysShown() failed");
}
String funkyPat;
funkyPat = pat.toPattern();
logln("Pattern is " + funkyPat);
String locPat;
locPat = pat.toLocalizedPattern();
logln("Localized pattern is " + locPat);
// ======= Test applyPattern()
logln("Testing applyPattern()");
String p1 = new String("#,##0.0#;(#,##0.0#)");
logln("Applying pattern " + p1);
pat.applyPattern(p1);
String s2;
s2 = pat.toPattern();
logln("Extracted pattern is " + s2);
if (!s2.equals(p1)) {
errln("ERROR: toPattern() result did not match pattern applied");
}
String p2 = new String("#,##0.0# FF;(#,##0.0# FF)");
logln("Applying pattern " + p2);
pat.applyLocalizedPattern(p2);
String s3;
s3 = pat.toLocalizedPattern();
logln("Extracted pattern is " + s3);
if (!s3.equals(p2)) {
errln("ERROR: toLocalizedPattern() result did not match pattern applied");
}
// ======= Test getStaticClassID()
// logln("Testing instanceof()");
// try {
// NumberFormat test = new DecimalFormat();
// if (! (test instanceof DecimalFormat)) {
// errln("ERROR: instanceof failed");
// }
// }
// catch (Exception e) {
// errln("ERROR: Couldn't create a DecimalFormat");
// }
}
public void TestRounding() {
double Roundingnumber = 2.55;
double Roundingnumber1 = -2.55;
//+2.55 results -2.55 results
double result[] = {
3, -3,
2, -2,
3, -2,
2, -3,
3, -3,
3, -3,
3, -3
};
DecimalFormat pat = new DecimalFormat();
String s = "";
s = pat.toPattern();
logln("pattern = " + s);
int mode;
int i = 0;
String message;
String resultStr;
for (mode = 0; mode < 7; mode++) {
pat.setRoundingMode(mode);
if (pat.getRoundingMode() != mode) {
errln(
"SetRoundingMode or GetRoundingMode failed for mode=" + mode);
}
//for +2.55 with RoundingIncrement=1.0
pat.setRoundingIncrement(1.0);
resultStr = pat.format(Roundingnumber);
message = "round(" + (double) Roundingnumber
+ "," + mode + ",FALSE) with RoundingIncrement=1.0==>";
verify(message, resultStr, result[i++]);
message = "";
resultStr = "";
//for -2.55 with RoundingIncrement=1.0
resultStr = pat.format(Roundingnumber1);
message = "round(" + (double) Roundingnumber1
+ "," + mode + ",FALSE) with RoundingIncrement=1.0==>";
verify(message, resultStr, result[i++]);
message = "";
resultStr = "";
}
}
/*Helper functions */
public void verify(String message, String got, double expected) {
logln(message + got + " Expected : " + (long)expected);
String expectedStr = "";
expectedStr=expectedStr + (long)expected;
if(!got.equals(expectedStr) ) {
errln("ERROR: Round() failed: " + message + got + " Expected : " + expectedStr);
}
}
}

View File

@ -0,0 +1,132 @@
/*****************************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestDecimalFormatSymbols.java,v $
* $Date: 2001/10/19 12:11:07 $
* $Revision: 1.1 $
*
*****************************************************************************************
**/
/**
* Port From: JDK 1.4b1 : java.text.Format.IntlTestDecimalFormatSymbols
* Source File: java/text/format/IntlTestDecimalFormatSymbols.java
**/
/*
@test 1.4 98/03/06
@summary test International Decimal Format Symbols
*/
/*
(C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
(C) Copyright IBM Corp. 1996, 1997, 2001 - All Rights Reserved
The original version of this source code and documentation is copyrighted and
owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These materials are
provided under terms of a License Agreement between Taligent and Sun. This
technology is protected by multiple US and International patents. This notice and
attribution to Taligent may not be removed.
Taligent is a registered trademark of Taligent, Inc.
*/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
import java.text.FieldPosition;
public class IntlTestDecimalFormatSymbols extends com.ibm.test.TestFmwk
{
public static void main(String[] args) throws Exception {
new IntlTestDecimalFormatSymbols().run(args);
}
// Test the API of DecimalFormatSymbols; primarily a simple get/set set.
public void TestSymbols()
{
DecimalFormatSymbols fr = new DecimalFormatSymbols(Locale.FRENCH);
DecimalFormatSymbols en = new DecimalFormatSymbols(Locale.ENGLISH);
if(en.equals(fr)) {
errln("ERROR: English DecimalFormatSymbols equal to French");
}
// just do some VERY basic tests to make sure that get/set work
char zero = en.getZeroDigit();
fr.setZeroDigit(zero);
if(fr.getZeroDigit() != en.getZeroDigit()) {
errln("ERROR: get/set ZeroDigit failed");
}
char group = en.getGroupingSeparator();
fr.setGroupingSeparator(group);
if(fr.getGroupingSeparator() != en.getGroupingSeparator()) {
errln("ERROR: get/set GroupingSeparator failed");
}
char decimal = en.getDecimalSeparator();
fr.setDecimalSeparator(decimal);
if(fr.getDecimalSeparator() != en.getDecimalSeparator()) {
errln("ERROR: get/set DecimalSeparator failed");
}
char perMill = en.getPerMill();
fr.setPerMill(perMill);
if(fr.getPerMill() != en.getPerMill()) {
errln("ERROR: get/set PerMill failed");
}
char percent = en.getPercent();
fr.setPercent(percent);
if(fr.getPercent() != en.getPercent()) {
errln("ERROR: get/set Percent failed");
}
char digit = en.getDigit();
fr.setDigit(digit);
if(fr.getPercent() != en.getPercent()) {
errln("ERROR: get/set Percent failed");
}
char patternSeparator = en.getPatternSeparator();
fr.setPatternSeparator(patternSeparator);
if(fr.getPatternSeparator() != en.getPatternSeparator()) {
errln("ERROR: get/set PatternSeparator failed");
}
String infinity = en.getInfinity();
fr.setInfinity(infinity);
String infinity2 = fr.getInfinity();
if(! infinity.equals(infinity2)) {
errln("ERROR: get/set Infinity failed");
}
String nan = en.getNaN();
fr.setNaN(nan);
String nan2 = fr.getNaN();
if(! nan.equals(nan2)) {
errln("ERROR: get/set NaN failed");
}
char minusSign = en.getMinusSign();
fr.setMinusSign(minusSign);
if(fr.getMinusSign() != en.getMinusSign()) {
errln("ERROR: get/set MinusSign failed");
}
// char exponential = en.getExponentialSymbol();
// fr.setExponentialSymbol(exponential);
// if(fr.getExponentialSymbol() != en.getExponentialSymbol()) {
// errln("ERROR: get/set Exponential failed");
// }
DecimalFormatSymbols foo = new DecimalFormatSymbols();
en = (DecimalFormatSymbols) fr.clone();
if(! en.equals(fr)) {
errln("ERROR: Clone failed");
}
}
}

View File

@ -0,0 +1,147 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestDecimalFormatSymbolsC.java,v $
* $Date: 2001/10/19 12:11:59 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : IntlTestDecimalFormatSymbols
* Source File: $ICU4CRoot/source/test/intltest/tsdcfmsy.cpp
**/
package com.ibm.icu.test.format;
import java.text.FieldPosition;
import com.ibm.util.*;
import java.util.Locale;
import com.ibm.text.*;
/**
* Tests for DecimalFormatSymbols
**/
public class IntlTestDecimalFormatSymbolsC extends com.ibm.test.TestFmwk {
public static void main(String[] args) throws Exception {
new IntlTestDecimalFormatSymbolsC().run(args);
}
/**
* Test the API of DecimalFormatSymbols; primarily a simple get/set set.
*/
public void TestSymbols() {
DecimalFormatSymbols fr = new DecimalFormatSymbols(Locale.FRENCH);
DecimalFormatSymbols en = new DecimalFormatSymbols(Locale.ENGLISH);
if (en.equals(fr)) {
errln("ERROR: English DecimalFormatSymbols equal to French");
}
// just do some VERY basic tests to make sure that get/set work
char zero = en.getZeroDigit();
fr.setZeroDigit(zero);
if (fr.getZeroDigit() != en.getZeroDigit()) {
errln("ERROR: get/set ZeroDigit failed");
}
char group = en.getGroupingSeparator();
fr.setGroupingSeparator(group);
if (fr.getGroupingSeparator() != en.getGroupingSeparator()) {
errln("ERROR: get/set GroupingSeparator failed");
}
char decimal = en.getDecimalSeparator();
fr.setDecimalSeparator(decimal);
if (fr.getDecimalSeparator() != en.getDecimalSeparator()) {
errln("ERROR: get/set DecimalSeparator failed");
}
char perMill = en.getPerMill();
fr.setPerMill(perMill);
if (fr.getPerMill() != en.getPerMill()) {
errln("ERROR: get/set PerMill failed");
}
char percent = en.getPercent();
fr.setPercent(percent);
if (fr.getPercent() != en.getPercent()) {
errln("ERROR: get/set Percent failed");
}
char digit = en.getDigit();
fr.setDigit(digit);
if (fr.getPercent() != en.getPercent()) {
errln("ERROR: get/set Percent failed");
}
char patternSeparator = en.getPatternSeparator();
fr.setPatternSeparator(patternSeparator);
if (fr.getPatternSeparator() != en.getPatternSeparator()) {
errln("ERROR: get/set PatternSeparator failed");
}
String infinity = en.getInfinity();
fr.setInfinity(infinity);
String infinity2 = fr.getInfinity();
if (!infinity.equals(infinity2)) {
errln("ERROR: get/set Infinity failed");
}
String nan = en.getNaN();
fr.setNaN(nan);
String nan2 = fr.getNaN();
if (!nan.equals(nan2)) {
errln("ERROR: get/set NaN failed");
}
char minusSign = en.getMinusSign();
fr.setMinusSign(minusSign);
if (fr.getMinusSign() != en.getMinusSign()) {
errln("ERROR: get/set MinusSign failed");
}
// char exponential = en.getExponentialSymbol();
// fr.setExponentialSymbol(exponential);
// if(fr.getExponentialSymbol() != en.getExponentialSymbol()) {
// errln("ERROR: get/set Exponential failed");
// }
DecimalFormatSymbols foo = new DecimalFormatSymbols();
en = (DecimalFormatSymbols) fr.clone();
if (!en.equals(fr)) {
errln("ERROR: Clone failed");
}
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
verify(34.5, "00.00", sym, "34.50");
sym.setDecimalSeparator('S');
verify(34.5, "00.00", sym, "34S50");
sym.setPercent('P');
verify(34.5, "00 %", sym, "3450 P");
sym.setCurrencySymbol("D");
verify(34.5, "\u00a4##.##", sym, "D34.5");
sym.setGroupingSeparator('|');
verify(3456.5, "0,000.##", sym, "3|456S5");
}
/** helper functions**/
public void verify(double value, String pattern, DecimalFormatSymbols sym, String expected) {
DecimalFormat df = new DecimalFormat(pattern, sym);
StringBuffer buffer = new StringBuffer("");
FieldPosition pos = new FieldPosition(-1);
buffer = df.format(value, buffer, pos);
if(!buffer.toString().equals(expected)){
errln("ERROR: format failed after setSymbols()\n Expected" +
expected + ", Got " + buffer);
}
}
}

View File

@ -0,0 +1,292 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestNumberFormat.java,v $
* $Date: 2001/10/19 12:12:47 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : IntlTestNumberFormat
* Source File: $ICU4CRoot/source/test/intltest/tsnmfmt.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
/**
* This test does round-trip testing (format -> parse -> format -> parse -> etc.) of
* NumberFormat.
*/
public class IntlTestNumberFormat extends com.ibm.test.TestFmwk {
public NumberFormat fNumberFormat = NumberFormat.getInstance();
public static void main(String[] args) throws Exception {
new IntlTestNumberFormat().run(args);
}
/*
* Internal use
**/
public void _testLocale(java.util.Locale locale, String localeName) {
String name;
// locale = java.util.Locale.getDefault();
// localeName = locale.getDisplayName();
name = "Number test";
logln(name + " ( " + localeName + " ) ");
fNumberFormat = NumberFormat.getInstance(locale);
TestFormat();
name = "Currency test";
logln(name + " (" + localeName + ")");
fNumberFormat = NumberFormat.getCurrencyInstance(locale);
TestFormat(/* par */);
name = "Percent test";
logln(name + " (" + localeName + ")");
fNumberFormat = NumberFormat.getPercentInstance(locale);
TestFormat(/* par */);
}
/**
* call TestFormat for currency, percent and plain number instances
**/
public void TestLocale() {
String name;
String localeName;
java.util.Locale locale = java.util.Locale.getDefault();
localeName = locale.getDisplayName();
name = "Number test";
logln(name + " ( " + localeName + " ) ");
fNumberFormat = NumberFormat.getInstance();
TestFormat();
name = "Currency test";
logln(name + " (" + localeName + ")");
fNumberFormat = NumberFormat.getCurrencyInstance();
TestFormat(/* par */);
name = "Percent test";
logln(name + " (" + localeName + ")");
fNumberFormat = NumberFormat.getPercentInstance();
TestFormat(/* par */);
}
/**
* call tryIt with many variations, called by testLocale
**/
public void TestFormat() {
if (fNumberFormat == null){
errln("**** FAIL: Null format returned by createXxxInstance.");
return;
}
DecimalFormat s = (DecimalFormat)fNumberFormat;
logln("pattern :" + s.toPattern());
tryIt(-2.02147304840132e-68);
tryIt(3.88057859588817e-68);
tryIt(-2.64651110485945e+65);
tryIt(9.29526819488338e+64);
tryIt(-2.02147304840132e-100);
tryIt(3.88057859588817e-096);
tryIt(-2.64651110485945e+306);
tryIt(9.29526819488338e+250);
tryIt(-9.18228054496402e+64);
tryIt(-9.69413034454191e+64);
tryIt(-9.18228054496402e+255);
tryIt(-9.69413034454191e+273);
tryIt(1.234e-200);
tryIt(-2.3e-168);
tryIt(Double.NaN);
tryIt(Double.POSITIVE_INFINITY);
tryIt(Double.NEGATIVE_INFINITY);
tryIt(251887531);
tryIt(5e-20 / 9);
tryIt(5e20 / 9);
tryIt(1.234e-50);
tryIt(9.99999999999996);
tryIt(9.999999999999996);
tryIt(Integer.MIN_VALUE);
tryIt(Integer.MAX_VALUE);
tryIt((double)Integer.MIN_VALUE);
tryIt((double)Integer.MAX_VALUE);
tryIt((double)Integer.MIN_VALUE - 1.0);
tryIt((double)Integer.MAX_VALUE + 1.0);
tryIt(5.0 / 9.0 * 1e-20);
tryIt(4.0 / 9.0 * 1e-20);
tryIt(5.0 / 9.0 * 1e+20);
tryIt(4.0 / 9.0 * 1e+20);
tryIt(2147483647.);
tryIt(0);
tryIt(0.0);
tryIt(1);
tryIt(10);
tryIt(100);
tryIt(-1);
tryIt(-10);
tryIt(-100);
tryIt(-1913860352);
for (int j = 0; j < 10; j++) {
double d = Math.random()*2e10 - 1e10;
tryIt(d);
}
}
/**
* perform tests using aNumber and fNumberFormat, called in many variations
**/
public void tryIt(double aNumber) {
final int DEPTH = 10;
double[] number = new double[DEPTH];
String[] string = new String[DEPTH];
int numberMatch = 0;
int stringMatch = 0;
boolean dump = false;
int i;
for (i = 0; i < DEPTH; i++) {
if (i == 0) {
number[i] = aNumber;
} else {
try {
number[i - 1] = fNumberFormat.parse(string[i - 1]).doubleValue();
} catch(java.text.ParseException pe) {
errln("**** FAIL: Parse of " + string[i-1] + " failed.");
dump = true;
break;
}
}
string[i] = fNumberFormat.format(number[i]);
if (i > 0)
{
if (numberMatch == 0 && number[i] == number[i-1])
numberMatch = i;
else if (numberMatch > 0 && number[i] != number[i-1])
{
errln("**** FAIL: Numeric mismatch after match.");
dump = true;
break;
}
if (stringMatch == 0 && string[i] == string[i-1])
stringMatch = i;
else if (stringMatch > 0 && string[i] != string[i-1])
{
errln("**** FAIL: String mismatch after match.");
dump = true;
break;
}
}
if (numberMatch > 0 && stringMatch > 0)
break;
if (i == DEPTH)
--i;
if (stringMatch > 2 || numberMatch > 2)
{
errln("**** FAIL: No string and/or number match within 2 iterations.");
dump = true;
}
if (dump)
{
for (int k=0; k<=i; ++k)
{
logln(k + ": " + number[k] + " F> " +
string[k] + " P> ");
}
}
}
}
/**
* perform tests using aNumber and fNumberFormat, called in many variations
**/
public void tryIt(int aNumber) {
long number;;
String stringNum = fNumberFormat.format(aNumber);
try {
number = fNumberFormat.parse(stringNum).longValue();
} catch (java.text.ParseException pe) {
errln("**** FAIL: Parse of " + stringNum + " failed.");
return;
}
if (number != aNumber) {
errln("**** FAIL: Parse of " + stringNum + " failed. Got:" + number
+ " Expected:" + aNumber);
}
}
/**
* test NumberFormat::getAvailableLocales
**/
public void TestAvailableLocales() {
final java.util.Locale[] locales = NumberFormat.getAvailableLocales();
int count = locales.length;
logln(count + " available locales");
if (count != 0)
{
String name;
String all = "";
for (int i = 0; i< count; ++i)
{
if (i!=0)
all += ", ";
all += locales[i].getDisplayName();
}
logln(all);
}
else
errln("**** FAIL: Zero available locales or null array pointer");
}
/**
* call testLocale for all locales
**/
public void TestMonster() {
final String SEP = "============================================================\n";
int count;
final java.util.Locale[] locales = NumberFormat.getAvailableLocales();
count = locales.length;
if (count != 0)
{
count = 3; // just test 3 locales
for (int i=0; i<count; ++i)
{
String name = locales[i].getDisplayName();
logln(SEP);
_testLocale(/* par, */locales[i], name);
}
}
logln(SEP);
}
}

View File

@ -0,0 +1,209 @@
/*****************************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/IntlTestNumberFormatAPI.java,v $
* $Date: 2001/10/19 12:13:23 $
* $Revision: 1.1 $
*
*****************************************************************************************
**/
/**
* Port From: JDK 1.4b1 : java.text.Format.IntlTestNumberFormatAPI
* Source File: java/text/format/IntlTestNumberFormatAPI.java
**/
/*
@test 1.4 98/03/06
@summary test International Number Format API
*/
/*
(C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
(C) Copyright IBM Corp. 1996, 1997, 2001 - All Rights Reserved
The original version of this source code and documentation is copyrighted and
owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These materials are
provided under terms of a License Agreement between Taligent and Sun. This
technology is protected by multiple US and International patents. This notice and
attribution to Taligent may not be removed.
Taligent is a registered trademark of Taligent, Inc.
*/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.ParseException;
public class IntlTestNumberFormatAPI extends com.ibm.test.TestFmwk
{
public static void main(String[] args) throws Exception {
new IntlTestNumberFormatAPI().run(args);
}
// This test checks various generic API methods in DecimalFormat to achieve 100% API coverage.
public void TestAPI()
{
logln("NumberFormat API test---"); logln("");
Locale.setDefault(Locale.ENGLISH);
// ======= Test constructors
logln("Testing NumberFormat constructors");
NumberFormat def = NumberFormat.getInstance();
NumberFormat fr = NumberFormat.getInstance(Locale.FRENCH);
NumberFormat cur = NumberFormat.getCurrencyInstance();
NumberFormat cur_fr = NumberFormat.getCurrencyInstance(Locale.FRENCH);
NumberFormat per = NumberFormat.getPercentInstance();
NumberFormat per_fr = NumberFormat.getPercentInstance(Locale.FRENCH);
NumberFormat integer = NumberFormat.getIntegerInstance();
NumberFormat int_fr = NumberFormat.getIntegerInstance(Locale.FRENCH);
// ======= Test equality
logln("Testing equality operator");
if( per_fr.equals(cur_fr) ) {
errln("ERROR: == failed");
}
// ======= Test various format() methods
logln("Testing various format() methods");
// final double d = -10456.0037; // this appears as -10456.003700000001 on NT
// final double d = -1.04560037e-4; // this appears as -1.0456003700000002E-4 on NT
final double d = -10456.00370000000000; // this works!
final long l = 100000000;
String res1 = new String();
String res2 = new String();
StringBuffer res3 = new StringBuffer();
StringBuffer res4 = new StringBuffer();
StringBuffer res5 = new StringBuffer();
StringBuffer res6 = new StringBuffer();
FieldPosition pos1 = new FieldPosition(0);
FieldPosition pos2 = new FieldPosition(0);
FieldPosition pos3 = new FieldPosition(0);
FieldPosition pos4 = new FieldPosition(0);
res1 = cur_fr.format(d);
logln( "" + d + " formatted to " + res1);
res2 = cur_fr.format(l);
logln("" + l + " formatted to " + res2);
res3 = cur_fr.format(d, res3, pos1);
logln( "" + d + " formatted to " + res3);
res4 = cur_fr.format(l, res4, pos2);
logln("" + l + " formatted to " + res4);
res5 = cur_fr.format(d, res5, pos3);
logln("" + d + " formatted to " + res5);
res6 = cur_fr.format(l, res6, pos4);
logln("" + l + " formatted to " + res6);
// ======= Test parse()
logln("Testing parse()");
// String text = new String("-10,456.0037");
String text = new String("-10456,0037");
ParsePosition pos = new ParsePosition(0);
ParsePosition pos01 = new ParsePosition(0);
double d1 = ((Number)fr.parseObject(text, pos)).doubleValue();
if(d1 != d) {
errln("ERROR: Roundtrip failed (via parse()) for " + text);
}
logln(text + " parsed into " + d1);
double d2 = fr.parse(text, pos01).doubleValue();
if(d2 != d) {
errln("ERROR: Roundtrip failed (via parse()) for " + text);
}
logln(text + " parsed into " + d2);
double d3 = 0;
try {
d3 = fr.parse(text).doubleValue();
}
catch (ParseException e) {
errln("ERROR: parse() failed");
}
if(d3 != d) {
errln("ERROR: Roundtrip failed (via parse()) for " + text);
}
logln(text + " parsed into " + d3);
// ======= Test getters and setters
logln("Testing getters and setters");
final Locale[] locales = NumberFormat.getAvailableLocales();
long count = locales.length;
logln("Got " + count + " locales" );
for(int i = 0; i < count; i++) {
String name;
name = locales[i].getDisplayName();
logln(name);
}
fr.setParseIntegerOnly( def.isParseIntegerOnly() );
if(fr.isParseIntegerOnly() != def.isParseIntegerOnly() ) {
errln("ERROR: setParseIntegerOnly() failed");
}
fr.setGroupingUsed( def.isGroupingUsed() );
if(fr.isGroupingUsed() != def.isGroupingUsed() ) {
errln("ERROR: setGroupingUsed() failed");
}
fr.setMaximumIntegerDigits( def.getMaximumIntegerDigits() );
if(fr.getMaximumIntegerDigits() != def.getMaximumIntegerDigits() ) {
errln("ERROR: setMaximumIntegerDigits() failed");
}
fr.setMinimumIntegerDigits( def.getMinimumIntegerDigits() );
if(fr.getMinimumIntegerDigits() != def.getMinimumIntegerDigits() ) {
errln("ERROR: setMinimumIntegerDigits() failed");
}
fr.setMaximumFractionDigits( def.getMaximumFractionDigits() );
if(fr.getMaximumFractionDigits() != def.getMaximumFractionDigits() ) {
errln("ERROR: setMaximumFractionDigits() failed");
}
fr.setMinimumFractionDigits( def.getMinimumFractionDigits() );
if(fr.getMinimumFractionDigits() != def.getMinimumFractionDigits() ) {
errln("ERROR: setMinimumFractionDigits() failed");
}
// ======= Test getStaticClassID()
// logln("Testing instanceof()");
// try {
// NumberFormat test = new DecimalFormat();
// if (! (test instanceof DecimalFormat)) {
// errln("ERROR: instanceof failed");
// }
// }
// catch (Exception e) {
// errln("ERROR: Couldn't create a DecimalFormat");
// }
}
}

View File

@ -0,0 +1,164 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/NumberFormatRegressionTest.java,v $
* $Date: 2001/10/19 12:14:05 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : NumberFormatRegressionTest
* Source File: $ICU4CRoot/source/test/intltest/numrgts.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
import java.util.Date;
import java.text.ParseException;
/**
* Performs regression test for MessageFormat
**/
public class NumberFormatRegressionTest extends com.ibm.test.TestFmwk {
public static void main(String[] args) throws Exception{
new NumberFormatRegressionTest().run(args);
}
/**
* alphaWorks upgrade
*/
public void Test4161100() {
NumberFormat nf = NumberFormat.getInstance(Locale.US);
nf.setMinimumFractionDigits(1);
nf.setMaximumFractionDigits(1);
double a = -0.09;
String s = nf.format(a);
logln(a + " x " +
((DecimalFormat) nf).toPattern() + " = " + s);
if (!s.equals("-0.1")) {
errln("FAIL");
}
}
/**
* DateFormat should call setIntegerParseOnly(TRUE) on adopted
* NumberFormat objects.
*/
public void TestJ691() {
Locale loc = new Locale("fr", "CH");
// set up the input date string & expected output
String udt = "11.10.2000";
String exp = "11.10.00";
// create a Calendar for this locale
Calendar cal = Calendar.getInstance(loc);
// create a NumberFormat for this locale
NumberFormat nf = NumberFormat.getInstance(loc);
// *** Here's the key: We don't want to have to do THIS:
//nf.setParseIntegerOnly(true);
// create the DateFormat
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, loc);
df.setCalendar(cal);
df.setNumberFormat(nf);
// set parsing to lenient & parse
Date ulocdat = new Date();
df.setLenient(true);
try {
ulocdat = df.parse(udt);
} catch (java.text.ParseException pe) {
errln(pe.getMessage());
}
// format back to a string
String outString = df.format(ulocdat);
if (!outString.equals(exp)) {
errln("FAIL: " + udt + " => " + outString);
}
}
/**
* Test getIntegerInstance();
*/
public void Test4408066() {
NumberFormat nf1 = NumberFormat.getIntegerInstance();
NumberFormat nf2 = NumberFormat.getIntegerInstance(Locale.CHINA);
//test isParseIntegerOnly
if (!nf1.isParseIntegerOnly() || !nf2.isParseIntegerOnly()) {
errln("Failed : Integer Number Format Instance should set setParseIntegerOnly(true)");
}
//Test format
{
double[] data = {
-3.75, -2.5, -1.5,
-1.25, 0, 1.0,
1.25, 1.5, 2.5,
3.75, 10.0, 255.5
};
String[] expected = {
"-4", "-2", "-2",
"-1", "0", "1",
"1", "2", "2",
"4", "10", "256"
};
for (int i = 0; i < data.length; ++i) {
String result = nf1.format(data[i]);
if (!result.equals(expected[i])) {
errln("Failed => Source: " + Double.toString(data[i])
+ ";Formatted : " + result
+ ";but expectted: " + expected[i]);
}
}
}
//Test parse, Parsing should stop at "."
{
String data[] = {
"-3.75", "-2.5", "-1.5",
"-1.25", "0", "1.0",
"1.25", "1.5", "2.5",
"3.75", "10.0", "255.5"
};
long[] expected = {
-3, -2, -1,
-1, 0, 1,
1, 1, 2,
3, 10, 255
};
for (int i = 0; i < data.length; ++i) {
Number n = null;
try {
n = nf1.parse(data[i]);
} catch (ParseException e) {
errln("Failed: " + e.getMessage());
}
if (!(n instanceof Long) || (n instanceof Integer)) {
errln("Failed: Integer Number Format should parse string to Long/Integer");
}
if (n.longValue() != expected[i]) {
errln("Failed=> Source: " + data[i]
+ ";result : " + n.toString()
+ ";expected :" + Long.toString(expected[i]));
}
}
}
}
}

View File

@ -0,0 +1,235 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/NumberFormatRoundTripTest.java,v $
* $Date: 2001/10/19 12:14:56 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
/**
* Porting From: ICU4C v1.8.1 : format : NumberFormatRoundTripTest
* Source File: $ICU4CRoot/source/test/intltest/nmfmtrt.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
/**
* Performs round-trip tests for NumberFormat
**/
public class NumberFormatRoundTripTest extends com.ibm.test.TestFmwk {
public double MAX_ERROR = 1e-14;
public double max_numeric_error = 0.0;
public double min_numeric_error = 1.0;
public boolean verbose = false;
public boolean STRING_COMPARE = false;
public boolean EXACT_NUMERIC_COMPARE = false;
public boolean DEBUG = false;
public boolean quick = true;
public static void main(String[] args) throws Exception {
new NumberFormatRoundTripTest().run(args);
}
public void TestNumberFormatRoundTrip() {
NumberFormat fmt = null;
logln("Default Locale");
logln("Default Number format");
fmt = NumberFormat.getInstance();
_test(fmt);
logln("Currency Format");
fmt = NumberFormat.getCurrencyInstance();
_test(fmt);
logln("Percent Format");
fmt = NumberFormat.getPercentInstance();
_test(fmt);
int locCount = 0;
final Locale[] loc = NumberFormat.getAvailableLocales();
if(quick) {
if(locCount > 5)
locCount = 5;
logln("Quick mode: only _testing first 5 Locales");
}
for(int i = 0; i < locCount; ++i) {
logln(loc[i].getDisplayName());
fmt = NumberFormat.getInstance(loc[i]);
_test(fmt);
fmt = NumberFormat.getCurrencyInstance(loc[i]);
_test(fmt);
fmt = NumberFormat.getPercentInstance(loc[i]);
_test(fmt);
}
logln("Numeric error " + min_numeric_error + " to " + max_numeric_error);
}
/**
* Return a random value from -range..+range.
*/
public double randomDouble(double range) {
return Math.random() * range;
}
public void _test(NumberFormat fmt) {
_test(fmt, Double.NaN);
_test(fmt, Double.POSITIVE_INFINITY);
_test(fmt, Double.NEGATIVE_INFINITY);
_test(fmt, 500);
_test(fmt, 0);
_test(fmt, -0);
_test(fmt, 0.0);
double negZero = 0.0;
negZero /= -1.0;
_test(fmt, negZero);
_test(fmt, 9223372036854775808.0d);
_test(fmt, -9223372036854775809.0d);
//_test(fmt, 6.936065876100493E74d);
// _test(fmt, 6.212122845281909E48d);
for (int i = 0; i < 10; ++i) {
_test(fmt, randomDouble(1));
_test(fmt, randomDouble(10000));
_test(fmt, Math.floor((randomDouble(10000))));
_test(fmt, randomDouble(1e50));
_test(fmt, randomDouble(1e-50));
_test(fmt, randomDouble(1e100));
_test(fmt, randomDouble(1e75));
_test(fmt, randomDouble(1e308) / ((DecimalFormat) fmt).getMultiplier());
_test(fmt, randomDouble(1e75) / ((DecimalFormat) fmt).getMultiplier());
_test(fmt, randomDouble(1e65) / ((DecimalFormat) fmt).getMultiplier());
_test(fmt, randomDouble(1e-292));
_test(fmt, randomDouble(1e-78));
_test(fmt, randomDouble(1e-323));
_test(fmt, randomDouble(1e-100));
_test(fmt, randomDouble(1e-78));
}
}
public void _test(NumberFormat fmt, double value) {
_test(fmt, new Double(value));
}
public void _test(NumberFormat fmt, long value) {
_test(fmt, new Long(value));
}
public void _test(NumberFormat fmt, Number value) {
logln("test data = " + value);
fmt.setMaximumFractionDigits(999);
String s, s2;
if (value.getClass().getName().equalsIgnoreCase("java.lang.Double"))
s = fmt.format(value.doubleValue());
else
s = fmt.format(value.longValue());
Number n = new Double(0);
boolean show = verbose;
if (DEBUG)
logln(
/*value.getString(temp) +*/ " F> " + s);
try {
n = fmt.parse(s);
} catch (java.text.ParseException e) {
System.out.println(e);
}
if (DEBUG)
logln(s + " P> " /*+ n.getString(temp)*/);
if (value.getClass().getName().equalsIgnoreCase("java.lang.Double"))
s2 = fmt.format(n.doubleValue());
else
s2 = fmt.format(n.longValue());
if (DEBUG)
logln(/*n.getString(temp) +*/ " F> " + s2);
if (STRING_COMPARE) {
if (!s.equals(s2)) {
errln("*** STRING ERROR \"" + s + "\" != \"" + s2 + "\"");
show = true;
}
}
if (EXACT_NUMERIC_COMPARE) {
if (value != n) {
errln("*** NUMERIC ERROR");
show = true;
}
} else {
// Compute proportional error
double error = proportionalError(value, n);
if (error > MAX_ERROR) {
errln("*** NUMERIC ERROR " + error);
show = true;
}
if (error > max_numeric_error)
max_numeric_error = error;
if (error < min_numeric_error)
min_numeric_error = error;
}
if (show)
logln(
/*value.getString(temp) +*/ value.getClass().getName() + " F> " + s + " P> " +
/*n.getString(temp) +*/ n.getClass().getName() + " F> " + s2);
}
public double proportionalError(Number a, Number b) {
double aa,bb;
if(a.getClass().getName().equalsIgnoreCase("java.lang.Double"))
aa = a.doubleValue();
else
aa = a.longValue();
if(a.getClass().getName().equalsIgnoreCase("java.lang.Double"))
bb = b.doubleValue();
else
bb = b.longValue();
double error = aa - bb;
if(aa != 0 && bb != 0)
error /= aa;
return Math.abs(error);
}
}

View File

@ -0,0 +1,696 @@
/*
*******************************************************************************
* Copyright (C) 2001, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
* $Source: /xsrl/Nsvn/icu/icu4j/src/com/ibm/icu/test/format/Attic/NumberFormatTest.java,v $
* $Date: 2001/10/19 12:15:50 $
* $Revision: 1.1 $
*
*****************************************************************************************
*/
/**
* Port From: ICU4C v1.8.1 : format : NumberFormatTest
* Source File: $ICU4CRoot/source/test/intltest/numfmtst.cpp
**/
package com.ibm.icu.test.format;
import com.ibm.text.*;
import com.ibm.util.*;
import java.util.Locale;
import java.text.ParsePosition;
import java.text.ParseException;
import java.text.FieldPosition;
public class NumberFormatTest extends com.ibm.test.TestFmwk {
public static void main(String[] args) throws Exception {
new NumberFormatTest().run(args);
}
// Test various patterns
public void TestPatterns() {
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
final String pat[] = { "#.#", "#.", ".#", "#" };
int pat_length = pat.length;
final String newpat[] = { "#0.#", "#0.", "#.0", "#" };
final String num[] = { "0", "0.", ".0", "0" };
for (int i=0; i<pat_length; ++i)
{
DecimalFormat fmt = new DecimalFormat(pat[i], sym);
String newp = fmt.toPattern();
if (!newp.equals(newpat[i]))
errln("FAIL: Pattern " + pat[i] + " should transmute to " + newpat[i] +
"; " + newp + " seen instead");
String s = ((NumberFormat)fmt).format(0);
if (!s.equals(num[i]))
{
errln("FAIL: Pattern " + pat[i] + " should format zero as " + num[i] +
"; " + s + " seen instead");
logln("Min integer digits = " + fmt.getMinimumIntegerDigits());
}
}
}
// Test exponential pattern
public void TestExponential() {
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
final String pat[] = { "0.####E0", "00.000E00", "##0.######E000", "0.###E0;[0.###E0]" };
int pat_length = pat.length;
double val[] = { 0.01234, 123456789, 1.23e300, -3.141592653e-271 };
int val_length = val.length;
final String valFormat[] = {
// 0.####E0
"1.234E-2", "1.2346E8", "1.23E300", "-3.1416E-271",
// 00.000E00
"12.340E-03", "12.346E07", "12.300E299", "-31.416E-272",
// ##0.######E000
"12.34E-003", "123.4568E006", "1.23E300", "-314.1593E-273",
// 0.###E0;[0.###E0]
"1.234E-2", "1.235E8", "1.23E300", "[3.142E-271]" };
double valParse[] =
{
0.01234, 123460000, 1.23E300, -3.1416E-271,
0.01234, 123460000, 1.23E300, -3.1416E-271,
0.01234, 123456800, 1.23E300, -3.141593E-271,
0.01234, 123500000, 1.23E300, -3.142E-271,
};
int lval[] = { 0, -1, 1, 123456789 };
int lval_length = lval.length;
final String lvalFormat[] = {
// 0.####E0
"0E0", "-1E0", "1E0", "1.2346E8",
// 00.000E00
"00.000E00", "-10.000E-01", "10.000E-01", "12.346E07",
// ##0.######E000
"0E000", "-1E000", "1E000", "123.4568E006",
// 0.###E0;[0.###E0]
"0E0", "[1E0]", "1E0", "1.235E8" };
int lvalParse[] =
{
0, -1, 1, 123460000,
0, -1, 1, 123460000,
0, -1, 1, 123456800,
0, -1, 1, 123500000,
};
int ival = 0, ilval = 0;
for (int p = 0; p < pat_length; ++p) {
DecimalFormat fmt = new DecimalFormat(pat[p], sym);
String pattern;
logln("Pattern \"" + pat[p] + "\" -toPattern-> \"" + fmt.toPattern() + "\"");
int v;
for (v = 0; v < val_length; ++v) {
String s;
s = ((NumberFormat) fmt).format(val[v]);
logln(" " + val[v] + " -format-> " + s);
if (!s.equals(valFormat[v + ival]))
errln("FAIL: Expected " + valFormat[v + ival]);
ParsePosition pos = new ParsePosition(0);
double a = fmt.parse(s, pos).doubleValue();
if (pos.getIndex() == s.length()) {
logln(" -parse-> " + Double.toString(a));
// Use epsilon comparison as necessary
} else
errln("FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + a);
}
for (v = 0; v < lval_length; ++v) {
String s;
s = ((NumberFormat) fmt).format(lval[v]);
logln(" " + lval[v] + "L -format-> " + s);
if (!s.equals(lvalFormat[v + ilval]))
errln("ERROR: Expected " + lvalFormat[v + ilval] + " Got: " + s);
ParsePosition pos = new ParsePosition(0);
long a = 0;
Number A = fmt.parse(s, pos);
if (A != null) {
a = A.longValue();
if (pos.getIndex() == s.length()) {
logln(" -parse-> " + a);
if (a != lvalParse[v + ilval])
errln("FAIL: Expected " + lvalParse[v + ilval]);
} else
errln("FAIL: Partial parse (" + pos.getIndex() + " chars) -> " + Long.toString(a));
} else {
errln("Fail to parse the string: " + s);
}
}
ival += val_length;
ilval += lval_length;
}
}
// Test the handling of quotes
public void TestQuotes() {
StringBuffer pat;
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
pat = new StringBuffer("a'fo''o'b#");
DecimalFormat fmt = new DecimalFormat(pat.toString(), sym);
String s = ((NumberFormat)fmt).format(123);
logln("Pattern \"" + pat + "\"");
logln(" Format 123 . " + s);
if (!s.equals("afo'ob123"))
errln("FAIL: Expected afo'ob123");
s ="";
pat = new StringBuffer("a''b#");
fmt = new DecimalFormat(pat.toString(), sym);
s = ((NumberFormat)fmt).format(123);
logln("Pattern \"" + pat + "\"");
logln(" Format 123 . " + s);
if (!s.equals("a'b123"))
errln("FAIL: Expected a'b123");
}
/**
* Test the handling of the currency symbol in patterns.
**/
public void TestCurrencySign() {
DecimalFormatSymbols sym = new DecimalFormatSymbols(Locale.US);
StringBuffer pat = new StringBuffer("");
char currency = 0x00A4;
// "\xA4#,##0.00;-\xA4#,##0.00"
pat.append(currency).append("#,##0.00;-").append(currency).append("#,##0.00");
DecimalFormat fmt = new DecimalFormat(pat.toString(), sym);
String s = ((NumberFormat) fmt).format(1234.56);
pat = new StringBuffer("");
logln("Pattern \"" + fmt.toPattern() + "\"");
logln(" Format " + 1234.56 + " . " + s);
if (!s.equals("$1,234.56"))
errln("FAIL: Expected $1,234.56");
s = "";
s = ((NumberFormat) fmt).format(-1234.56);
logln(" Format " + Double.toString(-1234.56) + " . " + s);
if (!s.equals("-$1,234.56"))
errln("FAIL: Expected -$1,234.56");
pat = new StringBuffer("");
// "\xA4\xA4 #,##0.00;\xA4\xA4 -#,##0.00"
pat.append(currency).append(currency).append(" #,##0.00;").append(currency).append(currency).append(" -#,##0.00");
fmt = new DecimalFormat(pat.toString(), sym);
s = "";
s = ((NumberFormat) fmt).format(1234.56);
logln("Pattern \"" + fmt.toPattern() + "\"");
logln(" Format " + Double.toString(1234.56) + " . " + s);
if (!s.equals("USD 1,234.56"))
errln("FAIL: Expected USD 1,234.56");
s = "";
s = ((NumberFormat) fmt).format(-1234.56);
logln(" Format " + Double.toString(-1234.56) + " . " + s);
if (!s.equals("USD -1,234.56"))
errln("FAIL: Expected USD -1,234.56");
}
/**
* Test localized currency patterns.
*/
public void TestCurrency() {
NumberFormat currencyFmt =
NumberFormat.getCurrencyInstance(Locale.CANADA_FRENCH);
String s;
s = currencyFmt.format(1.50);
logln("Un pauvre ici a..........." + s);
if (!s.equals("1,50 $"))
errln("FAIL: Expected 1,50 $");
s = "";
currencyFmt = NumberFormat.getCurrencyInstance(Locale.GERMANY);
s = currencyFmt.format(1.50);
logln("Un pauvre en Allemagne a.." + s);
if (!s.equals("1,50 DM"))
errln("FAIL: Expected 1,50 DM");
s = "";
currencyFmt = NumberFormat.getCurrencyInstance(Locale.FRANCE);
s = currencyFmt.format(1.50);
logln("Un pauvre en France a....." + s);
if (!s.equals("1,50 F"))
errln("FAIL: Expected 1,50 F");
}
/**
* Do rudimentary testing of parsing.
*/
public void TestParse() {
String arg = "0.0";
DecimalFormat format = new DecimalFormat("00");
double aNumber = 0l;
try {
aNumber = format.parse(arg).doubleValue();
} catch (java.text.ParseException e) {
System.out.println(e);
}
logln("parse(" + arg + ") = " + aNumber);
}
/**
* Test proper rounding by the format method.
*/
public void TestRounding487() {
NumberFormat nf = NumberFormat.getInstance();
roundingTest(nf, 0.00159999, 4, "0.0016");
roundingTest(nf, 0.00995, 4, "0.01");
roundingTest(nf, 12.3995, 3, "12.4");
roundingTest(nf, 12.4999, 0, "12");
roundingTest(nf, - 19.5, 0, "-20");
}
/**
* Test the functioning of the secondary grouping value.
*/
public void TestSecondaryGrouping() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
DecimalFormat f = new DecimalFormat("#,##,###", US);
expect(f, 123456789L, "12,34,56,789");
expectPat(f, "#,##,###");
f.applyPattern("#,###");
f.setSecondaryGroupingSize(4);
expect(f, 123456789L, "12,3456,789");
expectPat(f, "#,####,###");
NumberFormat g = NumberFormat.getInstance(new Locale("hi", "IN"));
String out = "";
long l = 1876543210L;
out = g.format(l);
// expect "1,87,65,43,210", but with Hindi digits
// 01234567890123
boolean ok = true;
if (out.length() != 14) {
ok = false;
} else {
for (int i = 0; i < out.length(); ++i) {
boolean expectGroup = false;
switch (i) {
case 1 :
case 4 :
case 7 :
case 10 :
expectGroup = true;
break;
}
// Later -- fix this to get the actual grouping
// character from the resource bundle.
boolean isGroup = (out.charAt(i) == 0x002C);
if (isGroup != expectGroup) {
ok = false;
break;
}
}
}
if (!ok) {
errln("FAIL Expected "+ l + " x hi_IN . \"1,87,65,43,210\" (with Hindi digits), got \""
+ out + "\"");
} else {
logln("Ok " + l + " x hi_IN . \"" + out + "\"");
}
}
public void roundingTest(NumberFormat nf, double x, int maxFractionDigits, final String expected) {
nf.setMaximumFractionDigits(maxFractionDigits);
String out = nf.format(x);
logln(x + " formats with " + maxFractionDigits + " fractional digits to " + out);
if (!out.equals(expected))
errln("FAIL: Expected " + expected);
}
/**
* Upgrade to alphaWorks
*/
public void expect(NumberFormat fmt, String str, int n) {
Long num = new Long(0);
try {
num = (Long)fmt.parse(str);
} catch (java.text.ParseException e) {
}
String pat = ((DecimalFormat)fmt).toPattern();
if (num.longValue() == n) {
logln("Ok \"" + str + "\" x " +
pat + " = " +
num.toString());
} else {
errln("FAIL \"" + str + "\" x " +
pat + " = " +
num.toString() + ", expected " + n + "L");
}
}
/**
* Upgrade to alphaWorks
*/
public void expect(NumberFormat fmt, final double n, final String exp) {
StringBuffer saw = new StringBuffer("");
FieldPosition pos = new FieldPosition(0);
saw = fmt.format(n, saw, pos);
String pat = ((DecimalFormat)fmt).toPattern();
if (saw.toString().equals(exp)) {
logln("Ok " + Double.toString(n) + " x " +
pat + " = \"" +
saw + "\"");
} else {
errln("FAIL " + Double.toString(n) + " x " +
pat + " = \"" +
saw + "\", expected \"" + exp + "\"");
}
}
/**
* Upgrade to alphaWorks
*/
public void TestExponent() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
DecimalFormat fmt1 = new DecimalFormat("0.###E0", US);
DecimalFormat fmt2 = new DecimalFormat("0.###E+0", US);
int n = 1234;
expect(fmt1, n, "1.234E3");
expect(fmt2, n, "1.234E+3");
expect(fmt1, "1.234E3", n);
expect(fmt1, "1.234E+3", n); // Either format should parse "E+3"
expect(fmt2, "1.234E+3", n);
}
/**
* Upgrade to alphaWorks
*/
public void TestScientific() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
// Test pattern round-trip
final String PAT[] = { "#E0", "0.####E0", "00.000E00", "##0.####E000", "0.###E0;[0.###E0]" };
int PAT_length = PAT.length;
int DIGITS[] = {
// min int, max int, min frac, max frac
0, 1, 0, 0, // "#E0"
1, 1, 0, 4, // "0.####E0"
2, 2, 3, 3, // "00.000E00"
1, 3, 0, 4, // "##0.####E000"
1, 1, 0, 3, // "0.###E0;[0.###E0]"
};
for (int i = 0; i < PAT_length; ++i) {
String pat = PAT[i];
DecimalFormat df = new DecimalFormat(pat, US);
String pat2 = df.toPattern();
if (pat.equals(pat2)) {
logln("Ok Pattern rt \"" + pat + "\" . \"" + pat2 + "\"");
} else {
errln("FAIL Pattern rt \"" + pat + "\" . \"" + pat2 + "\"");
}
// Make sure digit counts match what we expect
if (df.getMinimumIntegerDigits() != DIGITS[4 * i]
|| df.getMaximumIntegerDigits() != DIGITS[4 * i + 1]
|| df.getMinimumFractionDigits() != DIGITS[4 * i + 2]
|| df.getMaximumFractionDigits() != DIGITS[4 * i + 3]) {
errln("FAIL \""+ pat+ "\" min/max int; min/max frac = "
+ df.getMinimumIntegerDigits() + "/"
+ df.getMaximumIntegerDigits() + ";"
+ df.getMinimumFractionDigits() + "/"
+ df.getMaximumFractionDigits() + ", expect "
+ DIGITS[4 * i] + "/"
+ DIGITS[4 * i + 1] + ";"
+ DIGITS[4 * i + 2] + "/"
+ DIGITS[4 * i + 3]);
}
}
expect(new DecimalFormat("#E0", US), 12345.0, "1.2345E4");
expect(new DecimalFormat("0E0", US), 12345.0, "1E4");
// pattern of NumberFormat.getScientificInstance(Locale.US) = "0.######E0" not "#E0"
// so result = 1.234568E4 not 1.2345678901E4
//when the pattern problem is finalized, delete comment mark'//'
//of the following code
expect(NumberFormat.getScientificInstance(Locale.US), 12345.678901, "1.2345678901E4");
expect(new DecimalFormat("##0.###E0", US), 12345.0, "12.34E3");
expect(new DecimalFormat("##0.###E0", US), 12345.00001, "12.35E3");
expect(new DecimalFormat("##0.####E0", US), 12345, "12.345E3");
// pattern of NumberFormat.getScientificInstance(Locale.US) = "0.######E0" not "#E0"
// so result = 1.234568E4 not 1.2345678901E4
expect(NumberFormat.getScientificInstance(Locale.FRANCE), 12345.678901, "1,2345678901E4");
expect(new DecimalFormat("##0.####E0", US), 789.12345e-9, "789.12E-9");
expect(new DecimalFormat("##0.####E0", US), 780.e-9, "780E-9");
expect(new DecimalFormat(".###E0", US), 45678.0, ".457E5");
expect(new DecimalFormat(".###E0", US), 0, ".0E0");
/*
expect(new DecimalFormat[] { new DecimalFormat("#E0", US),
new DecimalFormat("##E0", US),
new DecimalFormat("####E0", US),
new DecimalFormat("0E0", US),
new DecimalFormat("00E0", US),
new DecimalFormat("000E0", US),
},
new Long(45678000),
new String[] { "4.5678E7",
"45.678E6",
"4567.8E4",
"5E7",
"46E6",
"457E5",
}
);
!
! Unroll this test into individual tests below...
!
*/
expect(new DecimalFormat("#E0", US), 45678000, "4.5678E7");
expect(new DecimalFormat("##E0", US), 45678000, "45.678E6");
expect(new DecimalFormat("####E0", US), 45678000, "4567.8E4");
expect(new DecimalFormat("0E0", US), 45678000, "5E7");
expect(new DecimalFormat("00E0", US), 45678000, "46E6");
expect(new DecimalFormat("000E0", US), 45678000, "457E5");
/*
expect(new DecimalFormat("###E0", US, status),
new Object[] { new Double(0.0000123), "12.3E-6",
new Double(0.000123), "123E-6",
new Double(0.00123), "1.23E-3",
new Double(0.0123), "12.3E-3",
new Double(0.123), "123E-3",
new Double(1.23), "1.23E0",
new Double(12.3), "12.3E0",
new Double(123), "123E0",
new Double(1230), "1.23E3",
});
!
! Unroll this test into individual tests below...
!
*/
expect(new DecimalFormat("###E0", US), 0.0000123, "12.3E-6");
expect(new DecimalFormat("###E0", US), 0.000123, "123E-6");
expect(new DecimalFormat("###E0", US), 0.00123, "1.23E-3");
expect(new DecimalFormat("###E0", US), 0.0123, "12.3E-3");
expect(new DecimalFormat("###E0", US), 0.123, "123E-3");
expect(new DecimalFormat("###E0", US), 1.23, "1.23E0");
expect(new DecimalFormat("###E0", US), 12.3, "12.3E0");
expect(new DecimalFormat("###E0", US), 123.0, "123E0");
expect(new DecimalFormat("###E0", US), 1230.0, "1.23E3");
/*
expect(new DecimalFormat("0.#E+00", US, status),
new Object[] { new Double(0.00012), "1.2E-04",
new Long(12000), "1.2E+04",
});
!
! Unroll this test into individual tests below...
!
*/
expect(new DecimalFormat("0.#E+00", US), 0.00012, "1.2E-04");
expect(new DecimalFormat("0.#E+00", US), 12000, "1.2E+04");
}
/**
* Upgrade to alphaWorks
*/
public void TestPad() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
expect(new DecimalFormat("*^##.##", US), 0, "^^^^0");
expect(new DecimalFormat("*^##.##", US), -1.3, "^-1.3");
expect(
new DecimalFormat("##0.0####E0*_ g-m/s^2", US),
0,
"0.0E0______ g-m/s^2");
expect(
new DecimalFormat("##0.0####E0*_ g-m/s^2", US),
1.0 / 3,
"333.333E-3_ g-m/s^2");
expect(new DecimalFormat("##0.0####*_ g-m/s^2", US), 0, "0.0______ g-m/s^2");
expect(
new DecimalFormat("##0.0####*_ g-m/s^2", US),
1.0 / 3,
"0.33333__ g-m/s^2");
// Test padding before a sign
final String formatStr = "*x#,###,###,##0.0#;*x(###,###,##0.0#)";
expect(new DecimalFormat(formatStr, US), -10, "xxxxxxxxxx(10.0)");
expect(new DecimalFormat(formatStr, US), -1000, "xxxxxxx(1,000.0)");
expect(new DecimalFormat(formatStr, US), -1000000, "xxx(1,000,000.0)");
expect(new DecimalFormat(formatStr, US), -100.37, "xxxxxxxx(100.37)");
expect(new DecimalFormat(formatStr, US), -10456.37, "xxxxx(10,456.37)");
expect(new DecimalFormat(formatStr, US), -1120456.37, "xx(1,120,456.37)");
expect(new DecimalFormat(formatStr, US), -112045600.37, "(112,045,600.37)");
expect(new DecimalFormat(formatStr, US), -1252045600.37, "(1,252,045,600.37)");
expect(new DecimalFormat(formatStr, US), 10, "xxxxxxxxxxxx10.0");
expect(new DecimalFormat(formatStr, US), 1000, "xxxxxxxxx1,000.0");
expect(new DecimalFormat(formatStr, US), 1000000, "xxxxx1,000,000.0");
expect(new DecimalFormat(formatStr, US), 100.37, "xxxxxxxxxx100.37");
expect(new DecimalFormat(formatStr, US), 10456.37, "xxxxxxx10,456.37");
expect(new DecimalFormat(formatStr, US), 1120456.37, "xxxx1,120,456.37");
expect(new DecimalFormat(formatStr, US), 112045600.37, "xx112,045,600.37");
expect(new DecimalFormat(formatStr, US), 10252045600.37, "10,252,045,600.37");
// Test padding between a sign and a number
final String formatStr2 = "#,###,###,##0.0#*x;(###,###,##0.0#*x)";
expect(new DecimalFormat(formatStr2, US), -10, "(10.0xxxxxxxxxx)");
expect(new DecimalFormat(formatStr2, US), -1000, "(1,000.0xxxxxxx)");
expect(new DecimalFormat(formatStr2, US), -1000000, "(1,000,000.0xxx)");
expect(new DecimalFormat(formatStr2, US), -100.37, "(100.37xxxxxxxx)");
expect(new DecimalFormat(formatStr2, US), -10456.37, "(10,456.37xxxxx)");
expect(new DecimalFormat(formatStr2, US), -1120456.37, "(1,120,456.37xx)");
expect(new DecimalFormat(formatStr2, US), -112045600.37, "(112,045,600.37)");
expect(new DecimalFormat(formatStr2, US), -1252045600.37, "(1,252,045,600.37)");
expect(new DecimalFormat(formatStr2, US), 10, "10.0xxxxxxxxxxxx");
expect(new DecimalFormat(formatStr2, US), 1000, "1,000.0xxxxxxxxx");
expect(new DecimalFormat(formatStr2, US), 1000000, "1,000,000.0xxxxx");
expect(new DecimalFormat(formatStr2, US), 100.37, "100.37xxxxxxxxxx");
expect(new DecimalFormat(formatStr2, US), 10456.37, "10,456.37xxxxxxx");
expect(new DecimalFormat(formatStr2, US), 1120456.37, "1,120,456.37xxxx");
expect(new DecimalFormat(formatStr2, US), 112045600.37, "112,045,600.37xx");
expect(new DecimalFormat(formatStr2, US), 10252045600.37, "10,252,045,600.37");
//testing the setPadCharacter(UnicodeString) and getPadCharacterString()
DecimalFormat fmt = new DecimalFormat("#", US);
char padString = 'P';
fmt.setPadCharacter(padString);
expectPad(fmt, "*P##.##", DecimalFormat.PAD_BEFORE_PREFIX, 5, padString);
fmt.setPadCharacter('^');
expectPad(fmt, "*^#", DecimalFormat.PAD_BEFORE_PREFIX, 1, '^');
//commented untill implementation is complete
/* fmt.setPadCharacter((UnicodeString)"^^^");
expectPad(fmt, "*^^^#", DecimalFormat.kPadBeforePrefix, 3, (UnicodeString)"^^^");
padString.remove();
padString.append((UChar)0x0061);
padString.append((UChar)0x0302);
fmt.setPadCharacter(padString);
UChar patternChars[]={0x002a, 0x0061, 0x0302, 0x0061, 0x0302, 0x0023, 0x0000};
UnicodeString pattern(patternChars);
expectPad(fmt, pattern , DecimalFormat.kPadBeforePrefix, 4, padString);
*/
}
/**
* Upgrade to alphaWorks
*/
public void TestPatterns2() {
DecimalFormatSymbols US = new DecimalFormatSymbols(Locale.US);
DecimalFormat fmt = new DecimalFormat("#", US);
char hat = 0x005E; /*^*/
expectPad(fmt, "*^#", DecimalFormat.PAD_BEFORE_PREFIX, 1, hat);
expectPad(fmt, "$*^#", DecimalFormat.PAD_AFTER_PREFIX, 2, hat);
expectPad(fmt, "#*^", DecimalFormat.PAD_BEFORE_SUFFIX, 1, hat);
expectPad(fmt, "#$*^", DecimalFormat.PAD_AFTER_SUFFIX, 2, hat);
expectPad(fmt, "$*^$#", -1);
expectPad(fmt, "#$*^$", -1);
expectPad(fmt, "'pre'#,##0*x'post'", DecimalFormat.PAD_BEFORE_SUFFIX, 12, (char) 0x0078 /*x*/);
expectPad(fmt, "''#0*x", DecimalFormat.PAD_BEFORE_SUFFIX, 3, (char) 0x0078 /*x*/);
expectPad(fmt, "'I''ll'*a###.##", DecimalFormat.PAD_AFTER_PREFIX, 10, (char) 0x0061 /*a*/);
fmt.applyPattern("AA#,##0.00ZZ");
fmt.setPadCharacter(hat);
fmt.setFormatWidth(10);
fmt.setPadPosition(DecimalFormat.PAD_BEFORE_PREFIX);
expectPat(fmt, "*^AA#,##0.00ZZ");
fmt.setPadPosition(DecimalFormat.PAD_BEFORE_SUFFIX);
expectPat(fmt, "AA#,##0.00*^ZZ");
fmt.setPadPosition(DecimalFormat.PAD_AFTER_SUFFIX);
expectPat(fmt, "AA#,##0.00ZZ*^");
// 12 3456789012
String exp = "AA*^#,##0.00ZZ";
fmt.setFormatWidth(12);
fmt.setPadPosition(DecimalFormat.PAD_AFTER_PREFIX);
expectPat(fmt, exp);
fmt.setFormatWidth(13);
// 12 34567890123
expectPat(fmt, "AA*^##,##0.00ZZ");
fmt.setFormatWidth(14);
// 12 345678901234
expectPat(fmt, "AA*^###,##0.00ZZ");
fmt.setFormatWidth(15);
// 12 3456789012345
expectPat(fmt, "AA*^####,##0.00ZZ"); // This is the interesting case
fmt.setFormatWidth(16);
// 12 34567890123456
expectPat(fmt, "AA*^#,###,##0.00ZZ");
}
public void expectPad(DecimalFormat fmt, String pat, int pos) {
expectPad(fmt, pat, pos, 0, (char)0);
}
public void expectPad(DecimalFormat fmt, final String pat, int pos, int width, final char pad) {
int apos = 0, awidth = 0;
char apadStr;
try {
fmt.applyPattern(pat);
apos = fmt.getPadPosition();
awidth = fmt.getFormatWidth();
apadStr = fmt.getPadCharacter();
} catch (Exception e) {
apos = -1;
awidth = width;
apadStr = pad;
}
if (apos == pos && awidth == width && apadStr == pad) {
logln("Ok \"" + pat + "\" pos="
+ apos + ((pos == -1) ? "" : " width=" + awidth + " pad=" + apadStr));
} else {
errln("FAIL \"" + pat + "\" pos=" + apos + " width="
+ awidth + " pad=" + apadStr + ", expected "
+ pos + " " + width + " " + pad);
}
}
public void expectPat(DecimalFormat fmt, final String exp) {
String pat = fmt.toPattern();
if (pat.equals(exp)) {
logln("Ok \"" + pat + "\"");
} else {
errln("FAIL \"" + pat + "\", expected \"" + exp + "\"");
}
}
}

File diff suppressed because it is too large Load Diff