杰瑞科技汇

Java double转int如何实现?

Of course! Converting a double to an int in Java is a common task, but it's important to understand the different methods and their implications, especially regarding precision and rounding.

Java double转int如何实现?-图1
(图片来源网络,侵删)

Here’s a complete guide covering the primary methods, best practices, and common pitfalls.

The Short Answer: The Main Methods

There are three primary ways to convert a double to an int in Java:

  1. Casting (Explicit Type Conversion): (int) myDouble
    • What it does: Truncates the decimal part. It discards everything after the decimal point without rounding.
    • Example: (int) 9.8 becomes 9.
  2. Math.round(): Math.round(myDouble)
    • What it does: Rounds to the nearest long (or int for an overload). It follows standard rounding rules (0.5 rounds up).
    • Example: Math.round(9.8) becomes 10. Math.round(9.2) becomes 9.
  3. Double.intValue(): myDouble.intValue()
    • What it does: This is a method on the Double wrapper object. It also truncates the decimal part, just like casting.
    • Example: new Double(9.8).intValue() becomes 9.

Detailed Breakdown of Each Method

Let's dive deeper into each method with examples.

Casting (int)

This is the most direct and performant way to get the integer part of a double. It performs truncation, not rounding.

Java double转int如何实现?-图2
(图片来源网络,侵删)

How it works: The (int) cast tells the JVM to take the double value and drop its fractional part, effectively moving towards zero on the number line.

Key Characteristics:

  • Truncates: 9 -> 10, -10.9 -> -10.
  • Fastest: It's a simple, direct operation with no overhead.
  • Potential for Data Loss: If the double value is outside the range of an int (i.e., > Integer.MAX_VALUE or < Integer.MIN_VALUE), it will not throw an exception. Instead, it will wrap around, leading to a completely incorrect and unexpected result.

Example:

public class DoubleToIntCasting {
    public static void main(String[] args) {
        double positiveDouble = 123.45;
        double negativeDouble = -123.45;
        double largeDouble = 1.23456789e10; // 12,345,678,900
        // Casting truncates the decimal part
        int positiveInt = (int) positiveDouble;
        int negativeInt = (int) negativeDouble;
        int largeInt = (int) largeDouble;
        System.out.println("Original positive double: " + positiveDouble);
        System.out.println("Casted to int: " + positiveInt); // Output: 123
        System.out.println("\nOriginal negative double: " + negativeDouble);
        System.out.println("Casted to int: " + negativeInt); // Output: -123
        System.out.println("\nOriginal large double: " + largeDouble);
        System.out.println("Casted to int: " + largeInt); // Output: -2147483648 (WRONG! Wrapped around)
    }
}

Math.round()

This method is used when you want to perform proper mathematical rounding.

How it works: It rounds the double to the nearest long. If you want an int, you must cast the result. It rounds "half-up" (e.g., 1.5 becomes 2, 2.5 becomes 3).

Key Characteristics:

  • Rounds: 5 -> 11, 4 -> 10.
  • Returns long: The Math.round(double) method returns a long. You must cast it to an int if you need an int.
  • Overflow Protection: If the double is too large to fit into a long, it will return Long.MAX_VALUE or Long.MIN_VALUE. This is much safer than casting.

Example:

public class DoubleToIntRounding {
    public static void main(String[] args) {
        double doubleToRound = 98.7;
        // Math.round() returns a long, so we must cast to int
        int roundedInt = (int) Math.round(doubleToRound);
        System.out.println("Original double: " + doubleToRound);
        System.out.println("Rounded to int: " + roundedInt); // Output: 99
        // Example with a value that rounds down
        double doubleToRoundDown = 98.2;
        int roundedDownInt = (int) Math.round(doubleToRoundDown);
        System.out.println("\nOriginal double: " + doubleToRoundDown);
        System.out.println("Rounded to int: " + roundedDownInt); // Output: 98
    }
}

Double.intValue()

This method is part of the Double wrapper class. It behaves identically to casting.

How it works: It converts the double value of the Double object to an int by truncating the fractional part.

Key Characteristics:

  • Truncates: Same as (int).
  • Object Overhead: It requires creating a Double object (if you don't already have one), which is less efficient than a direct cast.
  • Potential for Data Loss: Same as casting, it will wrap around on overflow.

Example:

public class DoubleToIntMethod {
    public static void main(String[] args) {
        double myDouble = 50.99;
        // Need to create a Double object first
        Double myDoubleObject = new Double(myDouble);
        // intValue() truncates the decimal part
        int convertedInt = myDoubleObject.intValue();
        System.out.println("Original double: " + myDouble);
        System.out.println("Converted via intValue(): " + convertedInt); // Output: 50
    }
}

Summary Table: Which Method to Use?

Method Behavior Return Type Overflow Behavior When to Use
(int) d Truncates (drops decimal) int Wraps around silently. When you specifically need the integer part (floor for positive, ceiling for negative) and performance is critical. Use with caution for large numbers.
Math.round(d) Rounds to nearest integer long Returns Long.MAX_VALUE / Long.MIN_VALUE. When you need mathematically correct rounding. Remember to cast the result to (int).
d.intValue() Truncates (drops decimal) int Wraps around silently. Rarely used in modern Java. Casting (int) is preferred for its simplicity and performance.

Important Considerations

Precision and Floating-Point Arithmetic

Remember that double values are not always precise representations of decimal numbers. Due to how they are stored in binary, small errors can creep in.

double a = 1.2000000000000001; // Very close to 1.2
double b = 1.2;
System.out.println((int) a); // Output: 1
System.out.println((int) b); // Output: 1
System.out.println(Math.round(a)); // Output: 1

In most cases, this isn't a problem, but be aware of it when dealing with calculations that result in values very close to a whole number.

Overflow

Casting and intValue() are dangerous with large numbers. Math.round() is much safer.

// A double that is larger than Integer.MAX_VALUE
double tooBig = 2.147483648e9; // 2,147,483,648
int maxInt = Integer.MAX_VALUE; // 2,147,483,647
// DANGEROUS: Wraps around
int dangerousCast = (int) tooBig;
System.out.println("Dangerous cast result: " + dangerousCast); // Output: -2147483648
// SAFER: Returns Long.MAX_VALUE
long safeRounded = Math.round(tooBig);
System.out.println("Safe round result: " + safeRounded); // Output: 2147483647

Best Practice Recommendation

  • If you need to truncate the decimal part (get the floor for positive numbers): Use casting (int) myDouble. It's the most efficient and idiomatic way. Just be 100% sure the value is within the int range.
  • If you need to round to the nearest integer: Use Math.round(myDouble) and cast the result to (int). It's the safest and most semantically correct choice for rounding.
分享:
扫描分享到社交APP
上一篇
下一篇