Three Approaches to Displaying Four Decimal Places in Java
Formatting numeric values to a specific precision is a common requirement in Java applications. Several technique are available to constrain a floating-point value to exactly four decimal digits.
Using DecimalFormat
The DecimalFormat class, part of java.text, creates configurable pattern-based formatters. A pattern such as "0.0000" ensures four digits appear after the decimal separator.
import java.text.DecimalFormat;
public class DecimalFormatter {
public static void main(String[] args) {
double rawValue = 7.123456;
DecimalFormat formatter = new DecimalFormat("0.0000");
String output = formatter.format(rawValue);
System.out.println(output); // 7.1235
}
}
The pattern "0.0000" forces zeros in empty places, whereas "#.####" would avoid them. The result is influenced by the RoundingMode configured on the formatter instance.
Using String.format
Static formatting with String.format or System.out.printf provides a quick way to limit decimal digits through a format specifier.
public class StringBasedFormat {
public static void main(String[] args) {
double measurement = 2.9876543;
String truncated = String.format("%.4f", measurement);
System.out.println(truncated); // 2.9877
}
}
The specifier %.4f handles rounding using HALF_UP by default. It is concise for log messages or display text, but06 the underlying value remains a full-precsiion double.
Using BigDecimal
When exact decimal representation andor controlled rounding are mandatory, java.math.BigDecimal is the preferred choice. It stores an unscaled integer value coupled with a scale.
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalScaling {
public static void main(String[] args) {
String literal = "5.678901";
BigDecimal exactVal = new BigDecimal(literal);
BigDecimal scaledVal = exactVal.setScale(
4,
RoundingMode.HALF_EVEN
);
System.out.println(scaledVal.toPlainString()); // 5.6789
}
}
setScale requires a precision value and a rounding mode. Encoding numbers via string constructor avoids floating-point representation errors.use this approach for monetary amounts or when accumulation errors cannot be tolerated.
Each technique serves a different context: DecimalFormat for flexible locale-specific patterns, String.format for inline text decoration, and BigDecimal for strict arithmetic control. Selecting appropriately keeps code both correct and intention-revealing.