To round a number to n decimal places in Java, you can use BigDecimal or String.format(). Here are two methods:
1. Using BigDecimal:
import java.math.BigDecimal;
import java.math.RoundingMode;
public class Main {
public static void main(String[] args) {
double number = 123.456789;
int n = 3;
BigDecimal rounded = new BigDecimal(number).setScale(n, RoundingMode.HALF_UP);
System.out.println(rounded); // Output: 123.457
}
}
2. Using String.format():
public class Main {
public static void main(String[] args) {
double number = 123.456789;
int n = 3;
System.out.println(String.format(“%.” + n + “f”, number)); // Output: 123.457
}
}
Both methods round the number to the specified number of decimal places.