Java教程

Java Math rint()

Java Math rint()

Java Math rint() 方法返回一个最接近指定值且等于数学整数的值。
也就是说,如果指定值为 5.8,则与数学整数最接近的值为 6.0。并且,对于值 5.4,与数学整数最接近的值是 5.0。
rint() 方法的语法是:
Math.rint(double value)
注意: rint() 方法是一个静态方法。因此,我们可以使用类名 Math 直接调用该方法。

rint() 参数

arg-返回其最接近的值等于数学整数的参数

rint() 返回值

返回与 arg 最接近的值,等于数学整数

示例: Java Math.rint()

class Main {
  public static void main(String[] args) {
    // Math.rint()
    // value greater than 5 after decimal
    System.out.println(Math.rint(1.878));  // 2.0
    // value less than 5 after decimal
    System.out.println(Math.rint(1.34));   // 1.0
    // value equal to 5 after decimal
    System.out.println(Math.rint(1.5));    // 2.0
    // value equal to 5 after decimal
    System.out.println(Math.rint(2.5));    // 2.0
  }
}
在上面的例子中,注意两个表达式,
// returns 2.0
Math.rint(1.5)
// returns 2.0
Math.rint(2.5)  
这里,在这两种情况下,小数点后的值都等于5。然而,
对于 1.5-方法是四舍五入 对于 2.5-该方法正在四舍五入。
这是因为,在 .5 的情况下,该方法四舍五入到最接近的偶数值。因此,在这两种情况下,该方法都会舍入到 2.0。

推荐教程

Math.round() Math.ceil() Math.floor()
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4