Java 程式將一個數字四捨五入到 n 個小數位
在本文中,我們將瞭解如何將數字四捨五入到 n 個小數位。十進位制值的四捨五入使用 CEIL 或 FLOOR 函式完成。
以下是其演示 −
輸入
假設我們的輸入是 −
Input : 3.1415
輸出
所需的輸出將是 −
Output : 3.2
演算法
Step 1 - START Step 2 - Declare a float variable values namely my_input. Step 3 - Read the required values from the user/ define the values Step 4 – Use the CEIL function to round the number to the required decimal places. In this example we are rounding up to 2 decimal places. Store the result. Step 5- Display the result Step 6- Stop
示例 1
在此,輸入是由使用者根據提示輸入的。您可以在我們的 編碼基礎工具
中即時嘗試此示例。
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Scanner;
public class DecimalFormatting {
public static void main(String[] args) {
float my_input;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A scanner object has been defined ");
System.out.print("Enter the first binary number : ");
my_input = my_scanner.nextFloat();
DecimalFormat roundup_decimal = new DecimalFormat("#.#");
roundup_decimal.setRoundingMode(RoundingMode.CEILING);
System.out.println("The rounded up value of " +my_input + " is ");
System.out.println(roundup_decimal.format(my_input));
}
}輸出
Required packages have been imported A scanner object has been defined Enter the first binary number : 3.1415 The decimal number is defined as 3.1415 The rounded up value of 3.1415 is 3.2
示例 2
在此,整數已預先定義,並訪問其值並顯示在控制檯上。
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class DecimalFormatting {
public static void main(String[] args) {
System.out.println("Required packages have been imported");
double my_input = 3.1415;
System.out.println("The decimal number is defined as " +my_input);
DecimalFormat roundup_decimal = new DecimalFormat("#.#");
roundup_decimal.setRoundingMode(RoundingMode.CEILING);
System.out.println("The rounded up value of " +my_input + " is ");
System.out.println(roundup_decimal.format(my_input));
}
}輸出
Required packages have been imported The decimal number is defined as 3.1415 The rounded up value of 3.1415 is 3.2
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP