What is NumberFormat/DecimalFormat in Java?

NumberFormat in Java is a class that provides methods to format and parse numbers for any locale. It is part of the java.text package. The DecimalFormat class is a subclass of NumberFormat that allows you to format decimal numbers according to custom patterns. This is particularly useful for displaying numbers in a user-friendly way, such as currency, percentages, and more.

Example of NumberFormat and DecimalFormat

import java.text.DecimalFormat; public class NumberFormatExample { public static void main(String[] args) { // Create a DecimalFormat instance DecimalFormat df = new DecimalFormat("#.##"); // Format a number double number = 12345.6789; String formattedNumber = df.format(number); // Print the formatted number System.out.println("Formatted Number: " + formattedNumber); } }

Java NumberFormat DecimalFormat number formatting Java programming