Java 实现 Double 类型数字四舍五入到最接近的 0.5
可以使用 Math 类的 round() 方法来实现该功能。该方法会对一个 double 类型的数字进行四舍五入。
具体实现如下:
public class Main {
public static void main(String[] args) {
double num1 = 3.4;
double num2 = 2.6;
double num3 = 2.3;
double num4 = 6.3;
double result1 = roundToNearestHalf(num1);
double result2 = roundToNearestHalf(num2);
double result3 = roundToNearestHalf(num3);
double result4 = roundToNearestHalf(num4);
System.out.println(result1); // 输出 3.0
System.out.println(result2); // 输出 2.5
System.out.println(result3); // 输出 2.0
System.out.println(result4); // 输出 6.0
}
public static double roundToNearestHalf(double num) {
double roundedNum = Math.round(num * 2) / 2.0;
return roundedNum;
}
}
在上述代码中,roundToNearestHalf() 方法会将输入的数字乘以 2,然后使用 Math 类的 round() 方法对结果进行四舍五入。最后,再将结果除以 2.0,得到最终的结果。
注意:在 Java 中,double 类型的数字是无法精确表示的,因此在进行计算时可能会存在一些误差。如果对精度要求较高,可以考虑使用 BigDecimal 类进行计算。
原文地址: http://www.cveoy.top/t/topic/v2A 著作权归作者所有。请勿转载和采集!