How to escape DecimalFormat pattern symbol in java

193 Views Asked by At

I want to format the number with DecimalFormat pattern symbol. Any idea to do??

Ex: ### 123 dollars and 00 cents ###

where 123 is need to formatted using DecimalFormat.format method

In C#, it is possible with escape("\") character. Is there any similar way in java?

double value = 123;
Console.WriteLine(value.ToString("\\#\\#\\# ##0 dollars and \\0\\0 cents \\#\\#\\#"));

Thanks in Advance

2

There are 2 best solutions below

0
On

Just concatenate the characters to the beginning and end of the string.

System.out.println("### " & formattedString & " ###")

It's more readable that way anyway.

0
On

You can do something like:

String pattern = "###,###,### Dolars ";
DecimalFormat decimalFormat = new DecimalFormat(pattern);
System.out.println("###" + decimalFormat.format(123456789) + "00 cents ###");

but you can't write XX cents dinamically.

This can be a workaround but it's still ugly:

String pattern = "###,###,###.###";
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('$');
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
System.out.println(decimalFormat.format(123456789.123) + " cents");

prints

123.456.789$123 cents.