Java 程式來舍入一個數字


java.lang.Math.round(float a)返回最接近引數的整數。透過新增 1/2,取結果中的向下取整,並將結果強制轉換為型別 int 來將結果舍入為整數。特殊情況 −

  • 如果該引數是 NaN,結果為 0。

  • 如果該引數為負無窮大或小於或等於 Integer.MIN_VALUE 的任意值,則結果與 Integer.MIN_VALUE 的值相等。

  • 如果該引數為正無窮大或大於或等於 Integer.MAX_VALUE 的任意值,則結果與 Integer.MAX_VALUE 的值相等。

示例

import java.util.Scanner;
public class RoundingDecimalPlaces {
   public static void main(String[] args) {
      System.out.println("Enter a string value ::");
      Scanner sc = new Scanner(System.in);
      float f = sc.nextFloat();
      System.out.println("Result of the given float after rounding:: " + Math.round(f));
   }
}

輸出

Enter a string value ::
44584.2257
Result of the given float after rounding:: 44584

更新於: 2020 年 3 月 13 日

583 次瀏覽

開始您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.