How To Show Negative Numbers Using Brackets With NumberFormatter In Java

By , 15 March 2012

How To Show Negative Numbers Using Brackets With NumberFormatter In Java

If you want to use parentheses around your negative numbers, you can do it in Java like this:

NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
if (formatter instanceof DecimalFormat) {
    DecimalFormat f = (DecimalFormat) formatter;
    f.setNegativePrefix("(" + f.getPositivePrefix());
    f.setNegativeSuffix(")");
}
String output = formatter.format(value);

This snippet will retain the localised currency formatting set by NumberFormat.

How To Show Negative Numbers Using Brackets With NumberFormatter In Java

About Roger Keays

How To Show Negative Numbers Using Brackets With NumberFormatter In Java

I guess I'd call myself a problem solver. Either that, or I'm some sort of organic machine designed to convert oxygen into carbon dioxide. You could go either way on that. I'm into languages and stuff. I wrote a book. It's okay, I guess. What else? I like reading, swimming, eating, and playing music. Satisfied? Sheesh.

Leave a Comment

Please visit https://rogerkeays.com/how-to-show-negative-numbers-using-brackets-with-numberformatter-in-java to add your comments.