// 示例代码:将 double 类型转换为 int 类型
public class DoubleToIntExample {
public static void main(String[] args) {
// 定义一个 double 类型的变量
double doubleValue = 123.456;
// 使用 (int) 强制类型转换,注意这会直接截断小数部分
int intValue = (int) doubleValue;
// 输出结果
System.out.println("原始 double 值: " + doubleValue);
System.out.println("转换后的 int 值: " + intValue);
// 如果需要四舍五入,可以使用 Math.round 方法
int roundedValue = (int) Math.round(doubleValue);
System.out.println("四舍五入后的 int 值: " + roundedValue);
}
}
(int) doubleValue
会直接截断小数部分,不会进行四舍五入。Math.round()
方法,它会返回一个 long
类型的结果,因此需要再强转为 int
。下一篇:java读取文件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站