杰瑞科技汇

Java float转int会丢失精度吗?

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

Java float转int会丢失精度吗?-图1
(图片来源网络,侵删)

Here’s a complete guide covering the best ways to do it, along with crucial details and examples.


The Short Answer: Use (int)

The most common and direct way to convert a float to an int is by casting. This is done by placing the target data type in parentheses before the value.

float myFloat = 42.8f;
int myInt = (int) myFloat;
System.out.println(myInt); // Output: 42

Key Behavior: This method truncates the decimal part. It doesn't round; it simply discards everything after the decimal point.


Important: Truncation vs. Rounding

This is the most critical concept to understand. Casting (int) performs truncation towards zero.

Java float转int会丢失精度吗?-图2
(图片来源网络,侵删)
Value Cast to int ((int) value) Rounded to int (Math.round(value))
9 5 6
1 5 5
5 5 6
-4.9 -4 -5
-4.1 -4 -4
-4.5 -4 -4 (or -5 in Java 8+)

As you can see, casting and rounding give different results, especially for negative numbers and values exactly at the .5 midpoint.


Method 1: Casting (int) - The Direct Approach

This is the best method when you explicitly want to discard the decimal part.

How it Works

The (int) cast operator tells the compiler to treat the float value as an int. Since int cannot store decimal places, the fractional part is simply dropped (truncated).

Example

public class FloatToIntCast {
    public static void main(String[] args) {
        float positiveFloat = 99.99f;
        float negativeFloat = -99.99f;
        float wholeNumberFloat = 50.0f;
        // Casting to int truncates the decimal part
        int positiveInt = (int) positiveFloat;
        int negativeInt = (int) negativeFloat;
        int wholeNumberInt = (int) wholeNumberFloat;
        System.out.println("Original float: " + positiveFloat);
        System.out.println("After cast to int: " + positiveInt);
        // Output:
        // Original float: 99.99
        // After cast to int: 99
        System.out.println("\nOriginal float: " + negativeFloat);
        System.out.println("After cast to int: " + negativeInt);
        // Output:
        // Original float: -99.99
        // After cast to int: -99
    }
}

Method 2: Math.round() - For Rounding

Use this method when you want to round the float to the nearest int. The rule is standard rounding: if the decimal is .5 or higher, it rounds up; otherwise, it rounds down.

Java float转int会丢失精度吗?-图3
(图片来源网络,侵删)

How it Works

Math.round() is an overloaded method.

  • Math.round(float f) returns an int.
  • Math.round(double d) returns a long.

For float to int conversion, you'll use the first one.

Example

public class FloatToIntRound {
    public static void main(String[] args) {
        float num1 = 3.14f;
        float num2 = 3.6f;
        float num3 = 3.5f;
        float num4 = -3.5f; // Note the behavior for .5 with negatives
        // Math.round() returns an int
        int int1 = Math.round(num1);
        int int2 = Math.round(num2);
        int int3 = Math.round(num3);
        int int4 = Math.round(num4);
        System.out.println("Math.round(" + num1 + ") = " + int1); // Output: 3
        System.out.println("Math.round(" + num2 + ") = " + int2); // Output: 4
        System.out.println("Math.round(" + num3 + ") = " + int3); // Output: 4 (Rounds up from .5)
        System.out.println("Math.round(" + num4 + ") = " + int4); // Output: -4 (Rounds towards "away from zero" for .5)
    }
}

Note on Java 8+: In Java 8 and later, Math.round() rounds a .5 value to the nearest even integer (this is known as "bankers' rounding"). For example, 5 rounds to 2, and 5 rounds to 4. In older versions, it always rounded up. For most use cases, this difference is minor.


Method 3: Math.floor() and Math.ceil() - For Floor and Ceiling

These are specialized methods for rounding in a specific direction.

Math.floor() - Rounds Down

Always rounds to the next lower integer, effectively discarding the decimal part and moving towards negative infinity.

float myFloat = 7.8f;
int myInt = (int) Math.floor(myFloat); // Cast is still needed as floor returns a double
System.out.println(myInt); // Output: 7
float myFloat2 = -7.8f;
int myInt2 = (int) Math.floor(myFloat2);
System.out.println(myInt2); // Output: -8

Important: Math.floor() returns a double, so you still need to cast the result to int.

Math.ceil() - Rounds Up

Always rounds to the next higher integer, moving towards positive infinity.

float myFloat = 7.2f;
int myInt = (int) Math.ceil(myFloat); // Cast is still needed as ceil returns a double
System.out.println(myInt); // Output: 8
float myFloat2 = -7.2f;
int myInt2 = (int) Math.ceil(myFloat2);
System.out.println(myInt2); // Output: -7

Important: Math.ceil() also returns a double, so a cast to int is required.


Potential Pitfall: Floating-Point Precision

Never rely on float or double for precise integer arithmetic, especially when dealing with money or exact counts. Due to how floating-point numbers are stored in binary, you can get unexpected results.

// A dangerous example
float f = 12345678.0f;
int i = (int) f;
System.out.println(i); // Expected: 12345678, Actual: 12345676 or similar

If you are starting with a number that is conceptually an integer, it's always better to store it in an int or long from the beginning.


Summary: Which Method Should I Use?

Your Goal Recommended Method Why
Discard the decimal part (e.g., getting the integer part of a coordinate). (int) myFloat It's the most direct, efficient, and clearly expresses the intent to truncate.
Round to the nearest whole number (e.g., calculating an average number of items). Math.round(myFloat) This is the standard rounding behavior everyone expects.
Always round down (e.g., calculating the number of full boxes you can fill). (int) Math.floor(myFloat) Explicitly states the "round down" logic.
Always round up (e.g., calculating the minimum number of boxes needed). (int) Math.ceil(myFloat) Explicitly states the "round up" logic.
分享:
扫描分享到社交APP
上一篇
下一篇