Wednesday, December 12, 2007

Java: Displaying negative percentage values in red and in parentheses

Recently, I was looking to write some code in Java for a financial application that would output percentage-format numbers, rounded to two decimal places, with negative numbers being displayed in parentheses and in red color. This was an internal application which only needed to work in the US/English locale.

For example, given the values 0.12345 and -0.12345, the formatted output needed to be, respectively:

12.35%
(12.35%)

Since for this application the output only needs to be formatted in the default locale, it can be done with one of the constructors of the Java DecimalFormat class. If the output will be displayed in a web browser (and only in a web browser), the HTML to display the red color for negative values can be embedded in the string passed to the NumberFormat constructors as well:

NumberFormat redNegativePercentTwoDecimalsFormat = new java.text.DecimalFormat(
  "0.00%;'<span style=\"color:#FF0000\">'(0.00%)'</span>'");

The created NumberFormat instance can then be used to output values in our desired format:

System.out.println(redNegativePercentTwoDecimalsFormat.format(0.12345f));
System.out.println(redNegativePercentTwoDecimalsFormat.format(-0.12345f));

Which produces the desired output (when viewed in a web browser):

12.35%
(12.35%)

No comments:

Post a Comment

Non-spammers: Thanks for visiting! Please go ahead and leave a comment; I read them all!

Attention SPAMMERS: I review all comments before they get posted, and I REPORT 100% of spam comments to Google as spam! Why not avoid getting your account banned as quickly -- and save us both a little time -- by skipping this comment form and moving on to the next one on your list? Thanks, and I hope you have a great day!