Number formatting Public

Number formatting

Description

How to use

Module Information

No tags specified
✅ 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);
Show less
No tags specified
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
Show less
No tags specified
import java.text.NumberFormat; import java.util.Locale; double value = 1234.56; NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US); System.out.println(nf.format(value)); Output: $1,234.56 Useful when you need locale-specific formatting.
Show less
No tags specified
✅ 4️⃣ BigDecimal (for precision) Best for financial calculations. import java.math.BigDecimal; import java.math.RoundingMode; BigDecimal value = new BigDecimal("12.34567"); value = value.setScale(2, RoundingMode.HALF_UP); System.out.println(value); 🔹 Prevents floating-point rounding issues.
Show less
Show full summary Hide full summary