在Java中,对于浮点数的四舍五入,会根据其精度的不同而有所差别。同时对于整数的四舍五入,可以使用Math.round()方法或强制类型转换实现。
示例代码如下:
// 浮点数四舍五入 double d1 = 3.14159; float f1 = 1.23456f;
// 保留2位小数 double roundedDouble = Math.round(d1 * 100) / 100.0; float roundedFloat = Math.round(f1 * 100) / 100f;
System.out.println(roundedDouble); // 3.14 System.out.println(roundedFloat); // 1.23
// 整数四舍五入 int i1 = 5; long l1 = 10L;
double roundedInt = Math.round(i1 / 2.0); long roundedLong = Math.round(l1 / 3.0);
System.out.println(roundedInt); // 3 System.out.println(roundedLong); // 3
// 强制类型转换 double d2 = 3.6; int i2 = (int) Math.round(d2); System.out.println(i2); // 4