The DecimalFormat class in Java is a powerful tool for formatting decimal numbers as strings. It's part of the java.text package and provides a wide range of formatting options, including specifying decimal separator, grouping size, and precision.

Whether you're dealing with currency, percentages, or scientific notation, DecimalFormat enables you to present numerical data in a human-readable and culturally appropriate manner. Let's dive into some examples to illustrate its capabilities.

Basic Formatting
At its core, DecimalFormat allows you to format a decimal number with specified precision and grouping size.

For instance, to format a double as a currency with two decimal places and a thousand separator:
```java import java.text.DecimalFormat; DecimalFormat df = new DecimalFormat("#,##0.00"); double number = 123456.789; String formattedNumber = df.format(number); ```
Pattern Syntax

The pattern syntax used by DecimalFormat is quite intuitive. Here are some examples:
#,##0- Thousands separator, no decimals (e.g., 1,234,567)#,##0.00- Thousands separator, two decimals (e.g., 1,234,567.89)0.00;- Custom decimal separator (semicolon in this case)######.##- No grouping, fixed precision
Locale-Aware Formatting

By using DecimalFormat with the current locale, you can ensure that the output respects the user's locale settings.
Here's how to create a locale-aware DecimalFormat:
```java import java.text.NumberFormat; import java.util.Locale; NumberFormat nf = NumberFormat.getNumberInstance(Locale.getDefault()); DecimalFormat df = (DecimalFormat) nf; ```
Advanced Formatting

Sometimes, you might need more control over the formatting. This is where DecimalFormatSymbols comes in handy.
Customizing Separators and Prefixes/Suffixes



















By creating a DecimalFormatSymbols instance and setting its properties, you can customize your format:
```java import java.text.DecimalFormatSymbols; DecimalFormatSymbols dfs = new DecimalFormatSymbols(); dfs.setDecimalSeparator('.'); dfs.setGroupingSeparator(','); dfs.setCurrencySymbol('$'); dfs.setMonetaryDecimalSeparator('.'); DecimalFormat df = new DecimalFormat("Β€,#00.00", dfs); ```
Scientific Notation
Formatting large or small numbers in scientific notation can be achieved using DecimalFormat with an appropriate pattern:
```java DecimalFormat df = new DecimalFormat("0.###########E0"); double number = 1234567890.12345; String formattedNumber = df.format(number); ```
The final result might vary depending on the locale settings, but using 0.###########E0 will show the number in scientific notation, with 9 significant figures and without a grouping separator.
In the vast landscape of Java's text formatting utilities, DecimalFormat stands out as an invaluable tool for converting numbers into human-readable strings. Its flexibility and comprehensiveness make it an essential part of any developer's toolkit. Happy formatting!