迹忆客 专注技术分享

当前位置:主页 > 学无止境 > 编程语言 > Java >

在 Java 中将 Double 转换为 Int

作者:迹忆客 最近更新:2023/09/09 浏览次数:

本文介绍了如何在 Java 中将 double 转换为 int。

double 类型用于存储浮点数,integer 类型用于存储非小数(整数)值。有几种方法可以将 double 类型转换为整数,例如类型转换,double 类的 intValue() 方法。让我们看一些例子。


在 Java 中使用类型转换将 double 转换为 int

这是在 Java 中将 double 转换为 int 的最简单方法。在这里,我们使用类型转换来获取整数结果。很好,但是它会截断实际值。它仅返回整数部分,不包括小数点。请参见下面的示例。

public class SimpleTesting{
    public static void main(String[] args) {
        double d_val = 12.90;
        System.out.println("Value in double: "+ d_val);
        int i_val = (int) d_val;
        System.out.println("Value in int: "+i_val);
    }
}

输出:

Value in double: 12.9
Value in int: 12

在 Java 中使用 round() 方法将 double 转换为 int

我们可以使用 Mathround() 方法将双精度型转换为整数类型。我们使用 round() 方法,因为它会将值四舍五入为最接近的整数。它有助于减少数据截断。请参见下面的示例。

public class SimpleTesting{
    public static void main(String[] args) {
        double d_val = 12.90;
        System.out.println("Value in double: "+ d_val);
        int i_val = (int) Math.round(d_val);
        System.out.println("Value in int: "+i_val);
    }
}

输出:

Value in double: 12.9
Value in int: 13

如你所见,在上面的示例中,强制转换返回 12,而在此示例中,强制转换返回 13,因为 round() 方法返回了舍入值。


使用 Java 中的 intValue() 方法将 double 转换为 int

Double 是 Java 中的包装类,它具有一种 intValue() 方法,该方法从 double 值中返回一个整数。这很容易,因为它是一个内置方法,因此我们不需要使用任何其他类,而只需使用该方法即可获得结果。请参见下面的示例。

public class SimpleTesting{
    public static void main(String[] args) {
        Double d_val = 12.90; // store into wrapper
        System.out.println("Value in double: "+ d_val);
        int i_val = d_val.intValue();
        System.out.println("Value in int: "+i_val);
    }
}

输出:

Value in double: 12.9
Value in int: 12

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便