java如何四舍五入
四舍五入方法
在Java中,实现四舍五入可以通过以下几种方式:
使用Math.round()
Math.round()是最直接的四舍五入方法,返回最接近参数的long或int值。
对于浮点数:

double num = 3.6;
long rounded = Math.round(num); // 结果为4
对于float类型:
float num = 3.4f;
int rounded = Math.round(num); // 结果为3
指定小数位数四舍五入
若需保留指定小数位数,结合BigDecimal或乘除运算实现:

double num = 3.14159;
// 使用BigDecimal保留两位小数
double result = BigDecimal.valueOf(num)
.setScale(2, RoundingMode.HALF_UP)
.doubleValue(); // 结果为3.14
或通过乘除运算:
double num = 3.14159;
double temp = num * 100; // 扩大到整数部分
double rounded = Math.round(temp) / 100.0; // 结果为3.14
使用DecimalFormat
通过格式化工具控制输出格式:
double num = 3.14159;
DecimalFormat df = new DecimalFormat("#.##");
String formatted = df.format(num); // 输出字符串"3.14"
注意事项
Math.round()对负数同样有效,例如Math.round(-1.6)结果为-2。- 若需银行家舍入(四舍六入五成双),使用
RoundingMode.HALF_EVEN。
以上方法可根据场景选择,简单四舍五入用Math.round(),高精度或格式化需求用BigDecimal或DecimalFormat。






