Trong bài viết này, chúng ta sẽ tìm hiểu cách làm tròn một số đến n chữ số thập phân trong Java. Việc làm tròn giá trị thập phân được thực hiện bằng hàm CEIL hoặc FLOOR.
Dưới đây là minh họa:
Đầu vào
Giả sử đầu vào là:
Đầu vào: 3.1415
Đầu ra
Kết quả mong đợi:
Đầu ra: 3.2
Thuật toán
Bước 1 - BẮT ĐẦU Bước 2 - Khai báo biến float: my_input Bước 3 - Đọc giá trị từ người dùng hoặc định nghĩa trước Bước 4 – Sử dụng hàm CEIL để làm tròn số đến số chữ số thập phân yêu cầu. Ví dụ này làm tròn lên 2 chữ số. Lưu kết quả. Bước 5 - Hiển thị kết quả Bước 6 - DỪNG
Ví dụ 1: Nhập từ bàn phím
Người dùng nhập giá trị dựa trên lời nhắc. Thử trực tiếp trong coding ground.
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: Giá trị định nghĩa trước
Số thực đã được định nghĩa trước, giá trị được truy xuất và hiển thị.
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