The code snippet below show us how to display or format negative number in parentheses. We start by defining the number format, the pattern has two parts separated by a semicolon. In the snippet we use the #,##0.00;(#,##0.00)
pattern. The pattern after the semicolon will be used to format negative number.
Next we create an instance of DecimalFormat
by calling getInstance()
method. We apply the format pattern for the formatter object by calling the applyPattern()
method of the DecimalFormat
instance. To format the number we simply call the format()
method and pass the number we are going to format for display or print out.
package org.kodejava.text;
import java.text.DecimalFormat;
public class NegativeNumberFormat {
// Pattern for formatting negative number.
public static final String PATTERN1 = "#,##0.00;(#,##0.00)";
public static final String PATTERN2 = "$#,##0.00;-$#,##0.00";
public static void main(String[] args) {
DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance();
df.applyPattern(PATTERN1);
// Format using parentheses
System.out.println("Positive: " + df.format(125));
System.out.println("Negative: " + df.format(-125));
// Format using currency symbol and minus sign
df.applyPattern(PATTERN2);
System.out.println("Positive: " + df.format(1000));
System.out.println("Negative: " + df.format(-1000));
}
}
The result of the code snippet above is:
Positive: 125.00
Negative: (125.00)
Positive: $1,000.00
Negative: -$1,000.00
If you need to parse negative numbers in parentheses to produce the represented number you can see the following example How do I parse negative number in parentheses?.
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Hi, your pattern is hardcoded in two points:
Commas, whitespace, points might be different in each country or locale. You hardcode $ sign. The currency can be different for each country and the position too. Somewhere currency sign is prefix, somewhere postfix.
Do you have other flexible solution?
Hi Vadim,
You can use the following code snippet:
The output of the code: