Display a percentage in Java

Java 8Object Oriented ProgrammingProgramming

To display a percentage in Java, use the following DecimalFormat.

DecimalFormat decFormat = new DecimalFormat("#%");

Since, we have used the DecimalFormat class, therefore do not forget to import the following package −

import java.text.DecimalFormat;

Now, let us learn how to display percentage −

decFormat.format(0.80)
decFormat.format(-0.19)
decFormat.format(1.88)

The above will be displayed as −

80%
-19%
188%

The following is the complete example −

Example

 Live Demo

import java.text.DecimalFormat;
public class Demo {
   public static void main(String[] argv) throws Exception {
      DecimalFormat decFormat = new DecimalFormat("#%");
      System.out.println(decFormat.format(0.80));
      System.out.println(decFormat.format(-0.19));
      System.out.println(decFormat.format(1.88));
      System.out.println(decFormat.format(0.9099));
      System.out.println(decFormat.format(12.788));
      System.out.println(decFormat.format(-9.678));
   }
}

Output

80%
-19%
188%
91%
1279%
-968%
raja
Published on 21-Dec-2018 06:29:46
Advertisements