杰瑞科技汇

Java中double和int类型如何转换?

Of course! In Java, double and int are two of the most fundamental data types. Understanding their differences and how to work with them is crucial for any Java developer.

Java中double和int类型如何转换?-图1
(图片来源网络,侵删)

Here's a complete breakdown covering everything from their definitions to conversions and best practices.


The Basics: int vs. double

Feature int (Integer) double (Double Precision Floating-Point)
Purpose For whole numbers (no decimal point). For numbers with decimal points.
Size 32 bits (4 bytes) 64 bits (8 bytes)
Range -2,147,483,648 to 2,147,483,647 Approx. ±4.9 x 10⁻³²⁴ to ±1.8 x 10³⁰⁸
Example 10, -50, 0, 3,000,000 14, -99.99, 5, 23e10 (scientific notation)
Default 0 0

Declaring and Initializing Variables

You declare variables using their type followed by the variable name.

public class NumberTypes {
    public static void main(String[] args) {
        // --- Declaration and Initialization for int ---
        int myInteger;
        myInteger = 10;
        // You can also declare and initialize in one line
        int anotherInteger = -50;
        // --- Declaration and Initialization for double ---
        double myDouble;
        myDouble = 3.14;
        // You can also use scientific notation
        double anotherDouble = 1.23e10; // This is 12,300,000,000.0
        System.out.println("Integer: " + myInteger);
        System.out.println("Another Integer: " + anotherInteger);
        System.out.println("Double: " + myDouble);
        System.out.println("Another Double: " + anotherDouble);
    }
}

The Critical Issue: Type Conversion

This is the most important part to understand. You cannot directly assign a double to an int because you might lose information (the decimal part).

a) Implicit Widening Conversion (Safe)

You can assign an int to a double without any issues. Java automatically converts the int to a double. This is called widening because you're moving from a smaller data type (int) to a larger one (double).

Java中double和int类型如何转换?-图2
(图片来源网络,侵删)
int myInt = 100;
double myDouble = myInt; // This is perfectly fine
System.out.println(myInt);      // Output: 100
System.out.println(myDouble);   // Output: 100.0 (the .0 is added)

b) Explicit Narrowing Conversion (Risky)

You cannot assign a double to an int directly. The compiler will give you an error because the double might have a fractional part that would be lost.

double myDouble = 9.8;
// int myInt = myDouble; // COMPILE ERROR: incompatible types: possible lossy conversion

To do this, you must perform an explicit cast. A cast tells the compiler, "I know what I'm doing. I'm okay with potentially losing data."

You do this by putting the target type in parentheses before the value.

double myDouble = 9.8;
int myInt = (int) myDouble; // Explicit cast
System.out.println(myDouble); // Output: 9.8
System.out.println(myInt);    // Output: 9 (The .8 is truncated/lost)

Warning: Casting truncates the number; it does not round it. 8 becomes 9, and 9 also becomes 9.

Java中double和int类型如何转换?-图3
(图片来源网络,侵删)

If you need to round, use the Math.round() method. Important: Math.round() returns a long, not an int, so you still need to cast if you want an int.

double myDouble = 9.8;
// Rounding to the nearest long, then casting to int
int roundedInt = (int) Math.round(myDouble);
System.out.println(roundedInt); // Output: 10
double myDouble2 = 9.4;
int roundedInt2 = (int) Math.round(myDouble2);
System.out.println(roundedInt2); // Output: 9

Arithmetic Operations

a) int Operations

When you perform arithmetic with ints, the result is always an int. Division behaves like standard integer division.

int a = 10;
int b = 3;
int sum = a + b;      // 13
int difference = a - b; // 7
int product = a * b;    // 30
int quotient = a / b;   // 3 (the .333... is truncated)
int remainder = a % b;  // 1 (the remainder of the division)

b) double Operations

When you perform arithmetic with doubles, the result is always a double.

double x = 10.5;
double y = 3.2;
double sum = x + y;      // 13.7
double difference = x - y; // 7.3
double product = x * y;    // 33.6
double quotient = x / y;   // 3.28125

c) Mixed Operations (The "Promotion Rule")

When you mix int and double in an operation, Java promotes the int to a double for the calculation. The final result will always be a double.

int myInt = 10;
double myDouble = 3.14;
// The 'myInt' is temporarily treated as 10.0
double result = myInt + myDouble; // 13.14 (double)
// Division is a common place to see this
int apples = 5;
double people = 2.0;
double applesPerPerson = apples / people; // 2.5 (double)
// Be careful! This is a common mistake:
int apples2 = 5;
int people2 = 2;
double applesPerPerson2 = apples2 / people2; // 2.0 (int division happens first!)

Parsing Strings to Numbers

Often, you'll get numbers as input from a user or a file in String format. You need to convert these to int or double.

int from a String

Use the Integer.parseInt() static method.

String numberStr = "123";
int number = Integer.parseInt(numberStr); // 123
// This will throw a NumberFormatException if the string is not a valid integer
// int badNumber = Integer.parseInt("hello");

double from a String

Use the Double.parseDouble() static method.

doubleStr = "98.6";
double number = Double.parseDouble(doubleStr); // 98.6
// This will also throw a NumberFormatException
// double badNumber = Double.parseDouble("abc");

Which One Should I Use? (Best Practices)

  • Use int when:

    • You are certain you will only be working with whole numbers.
    • Memory usage is a critical concern (though this is rarely an issue for single variables).
    • You need to use a number as an index for an array or a List.
    • You are counting things (e.g., number of items, loop counters).
  • Use double when:

    • You need to represent numbers with decimal points.
    • You are performing calculations that might result in fractions (e.g., averages, financial calculations, scientific data).
    • You are reading input from sources like user input or files, which are often read as strings and then parsed into doubles.

Summary

Task int double
Store a whole number int count = 100; double d = 100.0;
Store a decimal number Not possible double price = 19.99;
Assign int to double double d = myInt; (Implicit) N/A
Assign double to int int i = (int) myDouble; (Explicit, truncates) N/A
Divide 10 by 3 int result = 10 / 3; // Result is 3 double result = 10.0 / 3.0; // Result is 3.333...
Parse from String int i = Integer.parseInt("500"); double d = Double.parseDouble("3.14");
分享:
扫描分享到社交APP
上一篇
下一篇