在 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+ 次瀏覽

開啟你的 職業

完成課程獲得認證

開始
廣告