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

Roger Keays is an artist, an engineer, and a student of life. He has no fixed address and has left footprints on 40-something different countries around the world. Roger is addicted to surfing. His other interests are music, psychology, languages, the proper use of semicolons, and finding good food.

Leave a Comment

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