Formatting decimals and retaining two decimals in Java can be achieved in the following ways:
1. Use the DecimalFormat class
import ; import ; public class DecimalFormatExample { public static void main(String[] args) { double number = 3.1415; DecimalFormat df = new DecimalFormat("0.00"); (RoundingMode.HALF_UP); // Set rounding mode String formatted = (number); (formatted); // Output: 3.14 } }
illustrate:
Mode "0.00": Forced to retain two decimal places, not enough to make up for zeros (for example, 2.5 formatted to 2.50).
RoundingMode.HALF_UP: Rounding rule (3.145 → 3.15).
2. Use ()
public class StringFormatExample { public static void main(String[] args) { double number = 3.1415; String formatted = ("%.2f", number); (formatted); // Output: 3.14 } }
illustrate:
Format string "%.2f": Automatically retain two decimal places, and the zero is not enough to be filled.
Locale problem: The system locale setting is used by default. If you need to fix the decimal symbol to ., you can specify:
String formatted = (, "%.2f", number);
3. Use BigDecimal (high precision calculation)
import ; import ; public class BigDecimalExample { public static void main(String[] args) { double number = 3.145; BigDecimal bd = (number); bd = (2, RoundingMode.HALF_UP); String formatted = (); (formatted); // Output: 3.15 } }
illustrate:
(number): Avoid accuracy problems caused by direct use of new BigDecimal(double).
setScale(2, RoundingMode.HALF_UP): Sets the decimal places and rounding modes.
4. Use NumberFormat (localized format)
import ; import ; public class NumberFormatExample { public static void main(String[] args) { double number = 1234.567; NumberFormat nf = (); (2); (2); String formatted = (number); (formatted); // Output: 1,234.57 (including the thousandths delimiter) } }
illustrate:
setMinimumFractionDigits(2) and setMaximumFractionDigits(2): Fixed two decimal places.
: Specify the decimal symbol as . and the thousandth part is ,.
Summarize
method | Applicable scenarios | Features |
---|---|---|
DecimalFormat | Flexible custom formats (such as currency, percentage) | Requires mode setting, support complex format |
() | Quick and simple formatting | Concise code, suitable for basic needs |
BigDecimal | High-precision calculation (such as financial scenarios) | Avoid floating point accuracy issues |
NumberFormat | Localized formats (such as the thousandth separator) | Support internationalization and automatically handle regional differences |
The above is the detailed content of four methods for Java to format decimals and retain two decimals. For more information on Java to format decimals and retain two decimals, please pay attention to my other related articles!