DecimalFormat Class

How to use the DecimalFormat Class!
caution: advanced. unfun.
This class is used to format output with a specific number of digits before and after the decimal point.
It's really neat, and pretty easy to use. I say it's advanced but it's really pretty self explanatory.

Here's a reference chart for later use!
0    - Required digit. Print 0 if there isn't a digit in this place.
#    - Optional digit. Leave blank if there isn't a digit in this place.
%   - Multiplies the result by 100 and displays a percent sign.

In a nutshell, you can use this class to modify an existing int, double, or long variable and format it to only display certain digits. In the below example, you ask the program to read out the 'fahrenheit' variable and format it to display the last two digits after the decimal, even if none are given.


Note: In order to use this NumberFormat class, you must use the following import statement:
import java.text.DecimalFormat;
Type that above your main string args line in order to use this class.

Example 1:

 double fahrenheit = 212.5;
 DecimalFormat patternFormatter = new DecimalFormat ("#, ###.00");
 System.out.println("The temperature is "+patternFormatter.format(fahrenheit));

Output: The temperature is 212.50.
Because the last two digits are marked .00 it MUST display both of these digits, and if they don't exist, they will be displayed as .00


Example 2:
 double fahrenheit = 212;
 DecimalFormat patternFormatter = new DecimalFormat ("#, ###.00");
 System.out.println("The temperature is "+patternFormatter.format(fahrenheit));

Output: The temperature is 212.00.
Because the last two digits are marked .00 it MUST display both of these digits, and if they don't exist, they will be displayed as .00


Example 3:
 double fahrenheit = 212;
 DecimalFormat patternFormatter = new DecimalFormat ("#, ###.##");
 System.out.println("The temperature is "+patternFormatter.format(fahrenheit));

Output: The temperature is 212.
Because the last two digits after the decimal are marked .## the last two digits are optional, and so it will not print them if they are not present.


Example 4:
 double fahrenheit = 212.129831928;
 DecimalFormat patternFormatter = new DecimalFormat ("#, ###.##");
 System.out.println("The temperature is "+patternFormatter.format(fahrenheit));

Output: The temperature is 212.12.
Because the last two digits after the decimal are marked .##, the first two digits after the decimal are optional, but it will not print the remaining digits.


DETAILED VIDEO BELOW




  Note: In order to use this NumberFormat class, you must use the following import statement:
import java.text.DecimalFormat;
Type that above your main string args line in order to use this class.

2 comments: