Formatting a Negative Number Output with Parentheses in Java

Java 8Object Oriented ProgrammingProgramming

A negative number output can be shown using the Formatter object −

Formatter f = new Formatter();
f.format("%12.2f", -7.598);
System.out.println(f);

Try the below given code to format a Negative Number Output with Parentheses −

Formatter f = new Formatter();
f.format("%(d", -50);
System.out.println(f);

The following is an example −

Example

 Live Demo

import java.util.Formatter;
public class Demo {
   public static void main(String args[]) {
      Formatter f = new Formatter();
      f.format("% d", 50);
      System.out.println(f);
      // negative number inside parentheses
      f = new Formatter();
      f.format("%(d", -50);
      System.out.println(f);
   }
}

Output

50
(50)
raja
Published on 21-Dec-2018 11:55:51
Advertisements