Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java làm tròn một số đến n vị trí thập phân

Trong bài này, chúng ta sẽ hiểu cách làm tròn một số đến n chữ số thập phân. Việc làm tròn các giá trị thập phân được thực hiện bằng cách sử dụng các hàm CEIL hoặc FLOOR.

Dưới đây là một minh chứng về điều tương tự -

Đầu vào

Giả sử đầu vào của chúng tôi là -

Input : 3.1415

Đầu ra

Đầu ra mong muốn sẽ là -

Output : 3.2

Thuật toán

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

Ví dụ 1

Ở đây, đầu vào đang được người dùng nhập dựa trên lời nhắc. Bạn có thể thử trực tiếp ví dụ này trong công cụ nền tảng mã hóa của chúng tôi Chương trình Java làm tròn một số đến n vị trí thập phân .

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

Đầu ra

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

Ví dụ 2

Ở đây, số nguyên đã được xác định trước đó và giá trị của nó được truy cập và hiển thị trên bảng điều khiển.

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

Đầu ra

Required packages have been imported
The decimal number is defined as 3.1415
The rounded up value of 3.1415 is
3.2