Java Rounding: DecimalFormat Guide
In Java, the DecimalFormat class can be used to achieve rounding. Here are some common rounding methods:
- Using the Math.round() method:
double number = 3.14159;
long roundedNumber = Math.round(number);
System.out.println(roundedNumber); // 输出:3
In this example, the Math.round() method returns the closest long integer to the parameter, indicating rounding.
- Use the DecimalFormat class:
double number = 3.14159;
DecimalFormat df = new DecimalFormat("#.0");
double roundedNumber = Double.parseDouble(df.format(number));
System.out.println(roundedNumber); // 输出:3.1
In this example, the DecimalFormat class is used to format numbers by specifying a format, and then converting the formatted string to a double type using the Double.parseDouble() method.
- Using the BigDecimal class:
double number = 3.14159;
BigDecimal bd = new BigDecimal(number);
bd = bd.setScale(1, RoundingMode.HALF_UP);
double roundedNumber = bd.doubleValue();
System.out.println(roundedNumber); // 输出:3.1
In this example, the BigDecimal class offers the setScale() method to adjust the number of decimal places and specify the rounding mode. Using RoundingMode.HALF_UP indicates rounding up.
These are common rounding methods found in Java. Choose the appropriate method based on specific needs to implement rounding.