How to Display Percentages in Java
When you want to display a percentage in Java, you need to use a formatting method to change a number from a decimal value, such as "0.56" into a displayable string like "56%." Converting from a decimal to a percentage is done by moving the decimal point two places to the left and adding a percentage sign (%). In Java you can utilize the "format" method from the "DecimalFormat" class to automatically create percentages from decimals.
Instructions
-
-
1
Open your Java source file in an editor, such as Eclipse, Netbeans or JBuilder X.
-
2
Add the code "import java.text.DecimalFormat;" to the top of your source file (without quotes.) This provides you access to the Java "DecimalFormat" class, which has methods for formating and converting numbers into strings.
-
-
3
Set the formatting for your percentage conversion by adding the code "DecimalFormat dformat = new DecimalFormat("#%");" (without quotes) in the spot where you want to display the percentage. The "#%" signifies that the provided number will be displayed as a percentage by multipying the number by 100 and adding a trailing "%" symbol to the result.
-
4
Display your number as a percentage with the "println" method by adding the code "System.out.println(dformat(0.11));" to output "11%." The "println" method sends the string to Java's output stream. Replace "0.11" with the number you want to display.
-
5
Save the Java file, compile and run it to display your number as a percentage.
-
1