Java 提供的 Math.round() 函数用于对 double 和 float 类型的值进行四舍五入取整:如果参数为正数,返回最接近参数的整数,四舍五入。如果参数为负数,返回最接近参数的整数,并且四舍五入为偶数。
Java 四舍五入取整函数
Java 提供了 Math.round() 函数,用于对 double 和 float 类型的值进行四舍五入取整。
使用方法:
long round(double a) long round(float a)
返回值:
示例:
System.out.println(Math.round(2.5)); // 输出 3 System.out.println(Math.round(2.4)); // 输出 2 System.out.println(Math.round(-2.5)); // 输出 -2
注意:
Math.round() 函数对浮点数进行四舍五入,因此结果可能与数学上四舍五入的结果不同。Math.round(
) 函数的行为与 BigDecimal 类的 setScale() 方法类似。long 类型的值进行四舍五入,而只是返回该值。