// 示例代码:将 double 类型转换为 integer 类型
public class DoubleToIntegerExample {
public static void main(String[] args) {
// 定义一个 double 类型的变量
double doubleValue = 123.456;
// 使用 (int) 强制类型转换,直接截断小数部分
int intValue1 = (int) doubleValue;
System.out.println("使用强制类型转换: " + intValue1); // 输出 123
// 使用 Math.round() 方法,四舍五入
int intValue2 = (int) Math.round(doubleValue);
System.out.println("使用 Math.round(): " + intValue2); // 输出 123
// 使用 (int) 强制类型转换时需要注意负数的情况
double negativeDoubleValue = -123.456;
int negativeIntValue = (int) negativeDoubleValue;
System.out.println("负数的强制类型转换: " + negativeIntValue); // 输出 -123
// 使用 Math.round() 处理负数
int negativeRoundedIntValue = (int) Math.round(negativeDoubleValue);
System.out.println("负数的 Math.round(): " + negativeRoundedIntValue); // 输出 -123
}
}
(int)
直接将 double
类型转换为 int
类型。这种方式会直接截断小数部分,不会进行四舍五入。Math.round()
方法可以对 double
进行四舍五入后再转换为 int
。这个方法适用于需要四舍五入的场景。Math.round()
,在处理负数时都会按照相同的规则进行转换。上一篇:java 获取当前年月
下一篇:java anymatch
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站