May I know how I can escape a string to be passed into decimal format?
// currencySymbolPrefix can be any string.
NumberFormat numberFormat = new DecimalFormat(currencySymbolPrefix + "#,##0.00");
How can I escape currencySymbolPrefix
, so that it may contains any characters including '#', and will not be interpreted as one of the pattern.
Please do not suggest
NumberFormat numberFormat = new DecimalFormat("#,##0.00");
final String output = currencySymbolPrefix + numberFormat.format(number);
as my vendor's method only accept single NumberFormat.
You can use apostrophes to quote:
String pattern = "'" + currencySymbolPrefix + "'#,##0.00";
NumberFormat numberFormat = new DecimalFormat(pattern);
If currencySymbolPrefix
itself may contain apostrophes, you'd need to escape those by doubling them:
String pattern = "'" + currencySymbolPrefix.replace("'", "''") + "'#,##0.00";
The DecimalFormat
allows you to quote special characters to treat them literally.
Many characters in a pattern are taken literally; they are matched during parsing and output unchanged during formatting. Special characters, on the other hand, stand for other characters, strings, or classes of characters. They must be quoted, unless noted otherwise, if they are to appear in the prefix or suffix as literals.
'
can be used to quote special characters in a prefix or suffix, for example,"'#'#"
formats123
to"#123"
. To create a single quote itself, use two in a row:"# o''clock"
.
Thus, you can write a general purpose string escaper for DecimalFormat
like this:
// a general-purpose string escaper for DecimalFormat
public static String escapeDecimalFormat(String s) {
return "'" + s.replace("'", "''") + "'";
}
Then you can use it in your case like this:
String currencySymbolPrefix = "<'#'>";
NumberFormat numberFormat = new DecimalFormat(
escapeDecimalFormat(currencySymbolPrefix) + "#,##0.00"
);
System.out.println(numberFormat.format(123456.789));
// <'#'>123,456.79
DecimalFormat
It should be noted that for currency symbols, NumberFormat
does in fact have the method setCurrency(Currency)
. DecimalFormat
implements this method. If you are using one of the ISO 4217 currencies, you can use a java.util.Currency
instance to setCurrency
on a DecimalFormat
. This will take care of the symbol mapping etc for you too.
¤ (\u00A4)
is the currency sign, replaced by currency symbol. If doubled, replaced by international currency symbol. If present in a pattern, the monetary decimal separator is used instead of the decimal separator.
Here's an example:
NumberFormat numberFormat = new DecimalFormat("¤#,##0.00");
numberFormat.setCurrency(Currency.getInstance("USD"));
System.out.println(numberFormat.format(123456.789));
// $123,456.79
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With