在 Java 中舍入浮点数和双精度数


为了在 Java 中舍入浮点数和双精度数,我们使用 java.lang.Math.round() 方法。该方法接受 double 或 float 值并返回一个整数值。它返回最接近 number 的整数。这是通过在该数字上添加 ½ 然后对其取整来计算的。

声明 - java.lang.Math.round() 方法声明如下 -

public static int round(float a)
public static int round(double a)

其中 a 是要舍入的值。

我们来看看一个在 Java 中舍入浮点数和双精度数的程序。

示例

 现场演示

import java.lang.Math;
public class Example {
   public static void main(String[] args) {
      // declaring and initializing some double and values
      double x = 25.5;
      float y = 8.1f;
      // printing the rounded values
      System.out.println("The round-off of "+ x + " is "+ Math.round(x));
      System.out.println("The round-off of "+ y + " is "+ Math.round(y));
   }
}

输出

The round-off of 25.5 is 26
The round-off of 8.1 is 8

更新于: 2020-06-26

9K+ 次浏览

开启你的 职业

完成课程获得认证

开始
广告
© . All rights reserved.