Add the ability to override the number of fractional digits of a
NumberFormat instance.
Review by: shanjian@google.com
git-svn-id: https://google-web-toolkit.googlecode.com/svn/trunk@10754 8db76d5a-ed1c-0410-87a9-c151d255dfc7
diff --git a/user/src/com/google/gwt/i18n/client/NumberFormat.java b/user/src/com/google/gwt/i18n/client/NumberFormat.java
index 5424ed3..fafed9b 100644
--- a/user/src/com/google/gwt/i18n/client/NumberFormat.java
+++ b/user/src/com/google/gwt/i18n/client/NumberFormat.java
@@ -975,6 +975,37 @@
}
/**
+ * Change the number of fractional digits used for formatting with this
+ * instance.
+ *
+ * @param digits the exact number of fractional digits for formatted
+ * values; must be >= 0
+ * @return {@code this}, for chaining purposes
+ */
+ public NumberFormat overrideFractionDigits(int digits) {
+ return overrideFractionDigits(digits, digits);
+ }
+
+ /**
+ * Change the number of fractional digits used for formatting with this
+ * instance. Digits after {@code minDigits} that are zero will be omitted from
+ * the formatted value.
+ *
+ * @param minDigits the minimum number of fractional digits for formatted
+ * values; must be >= 0
+ * @param maxDigits the maximum number of fractional digits for formatted
+ * values; must be >= {@code minDigits}
+ * @return {@code this}, for chaining purposes
+ */
+ public NumberFormat overrideFractionDigits(int minDigits, int maxDigits) {
+ assert minDigits >= 0;
+ assert maxDigits >= minDigits;
+ minimumFractionDigits = minDigits;
+ maximumFractionDigits = maxDigits;
+ return this;
+ }
+
+ /**
* Parses text to produce a numeric value. A {@link NumberFormatException} is
* thrown if either the text is empty or if the parse does not consume all
* characters of the text.
diff --git a/user/test/com/google/gwt/i18n/client/NumberFormat_en_Test.java b/user/test/com/google/gwt/i18n/client/NumberFormat_en_Test.java
index f69c5cd..f5e7c54 100644
--- a/user/test/com/google/gwt/i18n/client/NumberFormat_en_Test.java
+++ b/user/test/com/google/gwt/i18n/client/NumberFormat_en_Test.java
@@ -152,6 +152,16 @@
assertEquals("¥1,235 JPY", str);
str = NumberFormat.getGlobalCurrencyFormat("CNY").format(1234.75);
assertEquals("¥1,234.75 CNY", str);
+
+ // Test overriding the number of fractional digits
+ formatter = NumberFormat.getCurrencyFormat("USD").overrideFractionDigits(0);
+ str = formatter.format(1234.556);
+ assertEquals("$1,235", str);
+ formatter = NumberFormat.getCurrencyFormat("USD").overrideFractionDigits(3, 4);
+ str = formatter.format(1234.556);
+ assertEquals("$1,234.556", str);
+ str = formatter.format(1234.55637);
+ assertEquals("$1,234.5564", str);
}
public void testExponential() {