// Java四舍五入示例代码
public class RoundExample {
public static void main(String[] args) {
double number = 12.3456;
// 使用Math.round()进行四舍五入,但需要注意它返回的是long类型
long rounded = Math.round(number);
System.out.println("Math.round(): " + rounded); // 输出: 12
// 如果需要保留小数位,可以先乘以10的n次方,再进行四舍五入,最后除以10的n次方
int decimalPlaces = 2; // 保留两位小数
double factor = Math.pow(10, decimalPlaces);
double roundedDecimal = Math.round(number * factor) / factor;
System.out.println("保留两位小数: " + roundedDecimal); // 输出: 12.35
// 使用BigDecimal进行更精确的四舍五入
import java.math.BigDecimal;
import java.math.RoundingMode;
BigDecimal bd = new BigDecimal(Double.toString(number));
bd = bd.setScale(decimalPlaces, RoundingMode.HALF_UP);
System.out.println("使用BigDecimal: " + bd.doubleValue()); // 输出: 12.35
}
}
long 类型,且不支持保留小数位。BigDecimal 类可以更精确地控制四舍五入的方式,并且支持多种舍入模式(如 HALF_UP)。上一篇:java if
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站