Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

java double转integer

作者:硝烟   发布日期:2025-03-29   浏览:28

// 示例代码:将 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
    }
}

解释说明:

  1. 强制类型转换:通过 (int) 直接将 double 类型转换为 int 类型。这种方式会直接截断小数部分,不会进行四舍五入。
  2. Math.round():使用 Math.round() 方法可以对 double 进行四舍五入后再转换为 int。这个方法适用于需要四舍五入的场景。
  3. 负数处理:无论是强制类型转换还是 Math.round(),在处理负数时都会按照相同的规则进行转换。

上一篇:java 获取当前年月

下一篇:java anymatch

大家都在看

java连接数据库的代码

ubuntu 卸载java

java sort用法

java collections.sort

java file类的方法

java 判断

java时间数据类型

java 时间加一天

java demo

java 截取

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站