在Java中,可以使用Math.round()
方法对整数进行四舍五入并保留指定小数位数。
double number = 3.14159;
int roundedNumber = (int) Math.round(number);
System.out.println(roundedNumber); // 输出:3
在上述示例中,Math.round()
方法将number
进行四舍五入,并返回最接近的整数值。然后,使用类型转换将结果转换为整数类型,并将其赋值给roundedNumber
变量。最后,通过调用System.out.println()
方法打印出结果。
在Java中,要将浮点数四舍五入到指定的小数位数,可以使用DecimalFormat类或BigDecimal类进行处理。
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
double number = 3.14159265358979323846;
DecimalFormat df = new DecimalFormat("#.######");
String roundedNumber = df.format(number);
System.out.println(roundedNumber);
}
}
DecimalFormat 的 setDecimalSeparatorAlwaysShown()
方法默认是 true
,即小数点后的零将始终显示出来。要避免输出后缀 0,您可以显式设置该属性为 false
。
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
double number = 123.4567;
DecimalFormat df = new DecimalFormat("#.######");
df.setDecimalSeparatorAlwaysShown(false);
String formattedNumber = df.format(number);
System.out.println(formattedNumber);
}
}