public class RoundExample {
public static void main(String[] args) {
double number = 12.3456;
int decimalPlace = 2; // 四舍五入到小数点后两位
// 使用 Math.round() 方法进行四舍五入
double roundedNumber = Math.round(number * Math.pow(10, decimalPlace)) / Math.pow(10, decimalPlace);
System.out.println("原始数字: " + number);
System.out.println("四舍五入后的数字: " + roundedNumber);
}
}
double number = 12.3456;
: 定义一个需要四舍五入的浮点数。int decimalPlace = 2;
: 指定四舍五入到小数点后几位(这里是两位)。number * Math.pow(10, decimalPlace)
:将数字乘以 10 的指定次方,移动小数点位置。Math.round()
:对调整后的大数值进行四舍五入。Math.pow(10, decimalPlace)
将小数点移回原位。这个代码段展示了如何使用 Math.round()
方法实现四舍五入的功能。
上一篇:java string转json
下一篇:java stack
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站