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. Since he left Australia in 2009, he has been living as a digital nomad in over 40 different countries around the world. Roger is addicted to surfing. His other interests are music, psychology, languages, 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.