Formatting a Negative Number Output with Parentheses in Java


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)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements