DecimalFormat
About
The DecimalFormat class in Java, part of the java.text package, is used for formatting and parsing decimal numbers in a locale-sensitive and customizable way. It allows precise control over the appearance of numeric values, such as rounding, grouping separators, and digit patterns.
DecimalFormatis a concrete subclass ofNumberFormatspecifically designed for formatting decimal numbers.It provides pattern-based formatting to define how numbers appear (e.g., decimal places, grouping separators, currency symbols).
The patterns can include digits, commas, dots, and special characters to create a specific format for numerical values.
Features
Pattern-Based Formatting: Allows defining custom patterns for numeric formats (e.g.,
"#.00"for two decimal places).Locale-Sensitive: Adapts grouping separators and decimal symbols based on the locale.
Customizable Symbols: Supports setting custom symbols like grouping separators, decimal points, and prefixes.
Rounding Behavior: Automatically rounds numbers based on the defined pattern.
Parsing Capability: Can parse formatted strings back into numerical values.
Thread-Safety: Not thread-safe but can be synchronized or used with thread-local storage.
Declaration
To use DecimalFormat, import it from the java.text package:
Common Methods
Formatting:
String format(double number): Formats adoubleinto aStringbased on the pattern.String format(long number): Formats alonginto aString.
Parsing:
Number parse(String source): Parses a formattedStringinto aNumber.
Customization:
setMaximumFractionDigits(int newValue): Sets the maximum number of digits allowed after the decimal point.setMinimumFractionDigits(int newValue): Sets the minimum number of digits required after the decimal point.setGroupingUsed(boolean newValue): Enables or disables the use of grouping separators (commas, spaces, etc.).
Symbols Customization:
setDecimalFormatSymbols(DecimalFormatSymbols newSymbols): Sets custom symbols like decimal points or grouping separators.
Usage
Basic Number Formatting
Output:
Customizing Patterns
Output:
Parsing Numbers
Output:
Custom Symbols
Output:
Real-World Example
Output:
Last updated