NumberFormat numberFormat = NumberFormat.getCurrencyInstance(Locale.US);
Number value = NumberFormat.getInstance().parse("-1234.876");
String output = numberFormat.format(value);
I have the code above. The output is -$1,234.88
. I want the output to be ($1,234.88)
. Is there a way to do this using NumberFormat, getCurrencyInstance, and Locale? (I only need this to work for USD in the US.)
I see that a Currency Format style of "account" should give me parentheses, but I'm not clear on whether I can use that with Locale. If I can, I don't understand how. I did try adding Locale locale = new Locale("en", "US","account");
before the other code.
I know I can use manipulate the String to get what I want, but I am hoping that there are Java methods to do it for me.
Note that this question is the opposite of the one at Java Currency Formatter adding parenthesis to the negative values. In Java 8, the parentheses were the default, and that user was asking how to get rid of the parenthesis and use the minus sign.
You can do:
NumberFormat.getCurrencyInstance(Locale.forLanguageTag("en-US-u-cf-account"));
https://www.jdoodle.com/ia/1yzp
The string argument passed to Locale.forLanguageTag
is a IETF BCP 47 language tag. Returns a Locale
object, which in turn we pass in a call to NumberFormat.getCurrencyInstance
.