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%)


0 comments:
Post a Comment