// 将 double 类型转换为 int 类型的示例代码
public class DoubleToIntExample {
public static void main(String[] args) {
// 定义一个 double 类型的变量
double doubleValue = 123.456;
// 使用 (int) 强制类型转换,直接截断小数部分
int intValue1 = (int) doubleValue;
System.out.println("使用强制类型转换: " + intValue1); // 输出: 123
// 使用 Math.floor() 方法,向下取整
int intValue2 = (int) Math.floor(doubleValue);
System.out.println("使用 Math.floor(): " + intValue2); // 输出: 123
// 使用 Math.ceil() 方法,向上取整
int intValue3 = (int) Math.ceil(doubleValue);
System.out.println("使用 Math.ceil(): " + intValue3); // 输出: 124
// 使用 Math.round() 方法,四舍五入
int intValue4 = (int) Math.round(doubleValue);
System.out.println("使用 Math.round(): " + intValue4); // 输出: 123
}
}
(int) doubleValue 直接将 double 类型转换为 int 类型,会截断小数部分,不会进行四舍五入。double 值的最大整数值(即向下取整)。double 值的最小整数值(即向上取整)。double 值进行四舍五入,并返回最接近的整数值。上一篇:java向下取整
下一篇:java时间
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站