✅ 1️⃣ String.format()
Simple and very common.
double value = 12.34567;
String result = String.format("%.2f", value);
System.out.println(result);
🔹 %.2f → 2 decimal places
🔹 Output: 12.35
You can also use:
System.out.printf("%.2f", value);
More flexible and commonly used in real applications.
import java.text.DecimalFormat;
DecimalFormat df = new DecimalFormat("0.00");
double value = 12.3;
System.out.println(df.format(value));
🔹 Output: 12.30
Pattern examples:
"0.00" → always 2 decimal places
"#.##" → up to 2 decimal places (does not force zeros)
"0.000" → 3 decimal places