How to round a number to n decimal places in Java
There are several ways to round a number to n decimal places in Java:
- Using
DecimalFormat
:
You can use the DecimalFormat
class to round a number to a specific number of decimal places. Here's an example:
double number = 123.4567;
int decimalPlaces = 2;
DecimalFormat df = new DecimalFormat("#." + String.format("%0" + decimalPlaces + "d", 0).replace("0","#"));
System.out.println(df.format(number));
This will output 123.46
.
- Using
String.format
:
You can use the String.format
method to round a number to a specific number of decimal places. Here's an example:
double number = 123.4567;
int decimalPlaces = 2;
String formattedNumber = String.format("%." + decimalPlaces + "f", number);
System.out.println(formattedNumber);
This will output 123.46
.
- Using
Math.round
:
You can use the Math.round
method to round a number to the nearest integer, and then divide the result by a power of 10 to get the number rounded to the desired number of decimal places. Here's an example:
double number = 123.4567;
int decimalPlaces = 2;
double factor = Math.pow(10, decimalPlaces);
double roundedNumber = (double) Math.round(number * factor) / factor;
System.out.println(roundedNumber);
This will output 123.46
.