How to use the DecimalFormat class in Java?
In Java, you can format numbers using the DecimalFormat class. Here are some common methods of using the DecimalFormat class.
- Instantiate a DecimalFormat object:
- Create a new Decimal Format object using the given pattern.
- The pattern is a string used to specify the format of the number.
- Format numbers:
- Format the number using the decimal format.
- The number is the digit to be formatted.
- Set the decimal places:
- df.setFractionDigits(minFractionDigits, maxFractionDigits);
- You can use these two methods to set the minimum and maximum number of decimal places.
- Enable thousand separators.
- Set the grouping to be used in the dataframe.
- This method will enable the use of thousands separators.
Here is a complete example:
import java.text.DecimalFormat;
public class DecimalFormatExample {
public static void main(String[] args) {
double number = 12345.6789;
String pattern = "#,##0.00";
DecimalFormat df = new DecimalFormat(pattern);
String formattedNumber = df.format(number);
System.out.println("Formatted Number: " + formattedNumber);
}
}
The output results are:
Formatted Number: 12,345.68
In this example, the number 12345.6789 is formatted as a string “12,345.68” with a thousand separator and two decimal places.