Java Math.round()、ceil()、floor()
這三個方法用於數值的捨入運算。
Math.round() 四捨五入
// 四捨五入到整數
System.out.println(Math.round(3.4)); // 3
System.out.println(Math.round(3.5)); // 4
System.out.println(Math.round(3.6)); // 4
// 負數
System.out.println(Math.round(-3.4)); // -3
System.out.println(Math.round(-3.5)); // -3(注意!)
System.out.println(Math.round(-3.6)); // -4
// float 回傳 int,double 回傳 long
int i = Math.round(3.5f); // 4
long l = Math.round(3.5); // 4L
Math.ceil() 無條件進位
// 向上取整(往正無限大方向)
System.out.println(Math.ceil(3.1)); // 4.0
System.out.println(Math.ceil(3.9)); // 4.0
System.out.println(Math.ceil(3.0)); // 3.0
// 負數
System.out.println(Math.ceil(-3.1)); // -3.0
System.out.println(Math.ceil(-3.9)); // -3.0
// 回傳 double
double result = Math.ceil(3.1); // 4.0
int intResult = (int) Math.ceil(3.1); // 4
Math.floor() 無條件捨去
// 向下取整(往負無限大方向)
System.out.println(Math.floor(3.1)); // 3.0
System.out.println(Math.floor(3.9)); // 3.0
System.out.println(Math.floor(3.0)); // 3.0
// 負數
System.out.println(Math.floor(-3.1)); // -4.0
System.out.println(Math.floor(-3.9)); // -4.0
// 回傳 double
double result = Math.floor(3.9); // 3.0
比較表
| 數值 | round() | ceil() | floor() | (int) 強轉 |
|---|---|---|---|---|
| 3.1 | 3 | 4.0 | 3.0 | 3 |
| 3.5 | 4 | 4.0 | 3.0 | 3 |
| 3.9 | 4 | 4.0 | 3.0 | 3 |
| -3.1 | -3 | -3.0 | -4.0 | -3 |
| -3.5 | -3 | -3.0 | -4.0 | -3 |
| -3.9 | -4 | -3.0 | -4.0 | -3 |
實用範例
小數點後幾位四捨五入
public static double roundToDecimalPlaces(double value, int places) {
double factor = Math.pow(10, places);
return Math.round(value * factor) / factor;
}
System.out.println(roundToDecimalPlaces(3.14159, 2)); // 3.14
System.out.println(roundToDecimalPlaces(3.14159, 3)); // 3.142
分頁計算
public static int getTotalPages(int totalItems, int pageSize) {
return (int) Math.ceil((double) totalItems / pageSize);
}
System.out.println(getTotalPages(100, 10)); // 10
System.out.println(getTotalPages(101, 10)); // 11
System.out.println(getTotalPages(95, 10)); // 10
價格處理
// 無條件捨去到元
public static int floorToYuan(double price) {
return (int) Math.floor(price);
}
// 無條件進位到元
public static int ceilToYuan(double price) {
return (int) Math.ceil(price);
}
System.out.println(floorToYuan(99.9)); // 99
System.out.println(ceilToYuan(99.1)); // 100
重點整理
round()四捨五入(float→int,double→long)ceil()向上取整(回傳 double)floor()向下取整(回傳 double)- 負數的行為需特別注意
- 小數點位數處理需搭配乘除運算