ในบทความนี้ เราจะเรียนรู้วิธีปัดเศษตัวเลขทศนิยมเป็นจำนวนตำแหน่งที่ต้องการในภาษา Java การปัดเศษทำได้โดยใช้ฟังก์ชัน CEIL หรือ FLOOR ผ่านคลาส DecimalFormat
ตัวอย่างการทำงาน
อินพุต:
Input : 3.1415
เอาต์พุต:
Output : 3.2
อัลกอริทึม
- เริ่มต้นโปรแกรม
- ประกาศตัวแปร float:
my_input - รับค่าจากผู้ใช้ หรือกำหนดค่าไว้ล่วงหน้า
- ใช้ฟังก์ชัน CEIL ผ่าน
DecimalFormatปัดเศษขึ้นตามตำแหน่งทศนิยมที่ต้องการ (ตัวอย่างปัด 1 ตำแหน่ง) - แสดงผลลัพธ์
- จบโปรแกรม
ตัวอย่างที่ 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));
}
}
ตัวอย่างที่ 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));
}
}
ทั้งสองตัวอย่างจะปัดเศษ 3.1415 เป็น 3.2 (ปัดขึ้น 1 ตำแหน่งทศนิยม)
หมายเหตุ: รูปแบบ #.# หมายถึงปัดเป็น 1 ตำแหน่งทศนิยม สามารถเปลี่ยนเป็น #.## สำหรับ 2 ตำแนได้