Java教程

Java Math round()

Java Math round()

在本教程中,我们将通过示例了解 Java Math.round() 方法。
round() 方法将指定值四舍五入到最接近的 int 或 long 值并返回它。也就是说,3.87 被四舍五入为 4,3.24 被四舍五入为 3。

示例

class Main {
  public static void main(String[] args) {
      double a = 3.87; System.out.println(Math.round(a)); 
  }
}
// Output: 4

Math.round() 的语法

round() 方法的语法是:
Math.round(value)
这里, round() 是一个静态方法。因此,我们使用类名访问该方法, Math

round() 参数

round() 方法接受一个参数。
value-要四舍五入的数字
注意: 值的数据类型应该是float或double。

round() 返回值

如果参数是 float,则返回 int 如果参数是 double,则返回 long
round() 方法:
如果小数点后的值大于或等于 5
1.5 => 2
1.7 => 2
则向上舍入
如果小数点后的值小于 5
1.3 => 1
,则向下舍入

示例 1: Java Math.round() 与 double

class Main {
  public static void main(String[] args) {
    // Math.round() method
    // value greater than 5 after decimal
    double a = 1.878;
    System.out.println(Math.round(a)); // 2 
    // value equals to 5 after decimal
     double b = 1.5;
    System.out.println(Math.round(b)); // 2 
    // value less than 5 after decimal
     double c = 1.34;
    System.out.println(Math.round(c)); // 1 
  }
}

示例 2: 带有浮点数的 Java Math.round()

class Main {
  public static void main(String[] args) {
    // Math.round() method
    // value greater than 5 after decimal
    float a = 3.78f;
    System.out.println(Math.round(a)); // 4 
    // value equals to 5 after decimal
    float b = 3.5f;
    System.out.println(Math.round(b)); // 4 
    // value less than 5 after decimal
    float c = 3.44f;
    System.out.println(Math.round(c)); // 3 
  }
}

推荐教程

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