Java Math round()

round() 方法将指定值四舍五入到最接近的 intlong 值并返回它。也就是说,3.87 四舍五入为 43.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 - 要四舍五入的数字

注意:value 的 数据类型 必须是 floatdouble


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() 与 float

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
} }

另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战