Home >Java >javaTutorial >How Can I Format Numbers in Java for Readability and Precision?
Formatting Numbers in Java
Formatting numbers in Java allows you to control how numbers are displayed to the user, often for readability or precision purposes. Here's how to do it:
Formatting a Number to a Specific Number of Decimal Places
To round and format a number to a specific number of decimal places, use BigDecimal or Math.round().
import java.math.BigDecimal; double r = 5.1234; int decimalPlaces = 2; BigDecimal bd = new BigDecimal(r); bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP); r = bd.doubleValue();
Formatting a Number with Commas
To add commas to a number, use DecimalFormat.
import java.text.DecimalFormat; DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" ); double dd = 100.2397; double dd2dec = new Double(df2.format(dd)).doubleValue();
Rounding Numbers
If rounding is necessary before formatting, you can use Math.round():
double r = 5.1234; double rounded = Math.round(r * 100.0f) / 100.0f;
Best Practices
The above is the detailed content of How Can I Format Numbers in Java for Readability and Precision?. For more information, please follow other related articles on the PHP Chinese website!