In this example we are going to learn to use a java.util.Formatter
to format negative number in parentheses. The Formatter
can use a format flags to format a value. To display a negative number in parentheses we can use the (
flag. This flag display negative number inside parentheses instead of using the -
symbol.
The following code snippet below will show you how to do it. We start the example by using the Formatter
object and simplified using the format()
method of the String
class.
package org.kodejava.util;
import java.util.Formatter;
import java.util.Locale;
public class FormatNegativeNumber {
public static void main(String[] args) {
// Creates an instance of Formatter, format the number using the
// format and print out the result.
Formatter formatter = new Formatter();
formatter.format("%(,.2f", -199.99f);
System.out.println("number1 = " + formatter);
// Use String.format() method instead of creating an instance of
// Formatter. Format a negative number using Germany locale.
String number2 = String.format(Locale.GERMANY, "%(,8.2f", -49.99);
System.out.println("number2 = " + number2);
// Format number using Indonesian locale. The thousand separator is "."
// in Indonesian number.
String number3 = String.format(new Locale("id", "ID"), "%(,d", -10000);
System.out.println("number3 = " + number3);
}
}
The result of this code snippet:
number1 = (199.99)
number2 = (49,99)
number3 = (10.000)