杰瑞科技汇

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 implications, as they can produce different results.

Java中float转int,精度丢失怎么办?-图1
(图片来源网络,侵删)

Here’s a comprehensive guide covering the main ways to convert a float to an int in Java, from the most common to the more nuanced.


Summary of Methods

Method How it Works Key Characteristic Example
(int) Casting Truncates the decimal part (rounds towards zero). Lossy. Discards the fractional part. (int) 5.9f -> 5
Math.round() Rounds to the nearest long, then cast to int. Rounding. Rounds to the closest integer. Math.round(5.5f) -> 6
Math.floor() Rounds down to the nearest double, then cast to int. Rounding Down. Always rounds towards negative infinity. (int) Math.floor(5.9f) -> 5
Math.ceil() Rounds up to the nearest double, then cast to int. Rounding Up. Always rounds towards positive infinity. (int) Math.ceil(5.1f) -> 6

Type Casting (int)

This is the most direct and common way to convert a float to an int. It performs a truncation, which means it simply chops off (discards) the decimal part of the number. This is equivalent to rounding towards zero.

Key Point: This method is lossy. You will lose any fractional information.

Syntax:

int intValue = (int) floatValue;

Example:

public class FloatToIntCast {
    public static void main(String[] args) {
        float positiveFloat = 5.99f;
        float negativeFloat = -5.99f;
        float wholeNumberFloat = 8.0f;
        // Casting to int truncates the decimal part
        int positiveInt = (int) positiveFloat; // Becomes 5
        int negativeInt = (int) negativeFloat; // Becomes -5
        int wholeNumberInt = (int) wholeNumberFloat; // Becomes 8
        System.out.println("Original float: " + positiveFloat + " -> Cast to int: " + positiveInt);
        System.out.println("Original float: " + negativeFloat + " -> Cast to int: " + negativeInt);
        System.out.println("Original float: " + wholeNumberFloat + " -> Cast to int: " + wholeNumberInt);
    }
}

Output:

Java中float转int,精度丢失怎么办?-图2
(图片来源网络,侵删)
Original float: 5.99 -> Cast to int: 5
Original float: -5.99 -> Cast to int: -5
Original float: 8.0 -> Cast to int: 8

Math.round()

This method is used when you want to round the float to the nearest integer before converting it.

How it works:

  1. Math.round(float) returns a long.
  2. If the decimal part is .5 or greater, it rounds up.
  3. If the decimal part is less than .5, it rounds down.
  4. You must then cast the returned long to an int.

Key Point: This method performs rounding. Be aware of potential overflow if the float is very large (e.g., Float.MAX_VALUE).

Syntax:

int intValue = (int) Math.round(floatValue);

Example:

public class FloatToIntRound {
    public static void main(String[] args) {
        float num1 = 5.4f; // Rounds down
        float num2 = 5.5f; // Rounds up
        float num3 = 5.6f; // Rounds up
        float num4 = -5.5f; // Rounds away from zero (to -6)
        int int1 = (int) Math.round(num1); // Becomes 5
        int int2 = (int) Math.round(num2); // Becomes 6
        int int3 = (int) Math.round(num3); // Becomes 6
        int int4 = (int) Math.round(num4); // Becomes -6
        System.out.println("Original float: " + num1 + " -> Rounded int: " + int1);
        System.out.println("Original float: " + num2 + " -> Rounded int: " + int2);
        System.out.println("Original float: " + num3 + " -> Rounded int: " + int3);
        System.out.println("Original float: " + num4 + " -> Rounded int: " + int4);
    }
}

Output:

Java中float转int,精度丢失怎么办?-图3
(图片来源网络,侵删)
Original float: 5.4 -> Rounded int: 5
Original float: 5.5 -> Rounded int: 6
Original float: 5.6 -> Rounded int: 6
Original float: -5.5 -> Rounded int: -6

Math.floor() and Math.ceil()

These methods give you more control over the direction of rounding.

Math.floor() (Rounds Down)

Math.floor() always rounds a number down to the nearest integer. The result is a double, which you must then cast to int.

Key Point: Rounds towards negative infinity.

Example:

public class FloatToIntFloor {
    public static void main(String[] args) {
        float num1 = 5.9f; // Rounds down to 5
        float num2 = 5.1f; // Rounds down to 5
        float num3 = -5.1f; // Rounds down to -6 (more negative)
        int int1 = (int) Math.floor(num1); // Becomes 5
        int int2 = (int) Math.floor(num2); // Becomes 5
        int int3 = (int) Math.floor(num3); // Becomes -6
        System.out.println("Original float: " + num1 + " -> Floored int: " + int1);
        System.out.println("Original float: " + num2 + " -> Floored int: " + int2);
        System.out.println("Original float: " + num3 + " -> Floored int: " + int3);
    }
}

Output:

Original float: 5.9 -> Floored int: 5
Original float: 5.1 -> Floored int: 5
Original float: -5.1 -> Floored int: -6

Math.ceil() (Rounds Up)

Math.ceil() always rounds a number up to the nearest integer. The result is a double, which you must then cast to int.

Key Point: Rounds towards positive infinity.

Example:

public class FloatToIntCeil {
    public static void main(String[] args) {
        float num1 = 5.1f; // Rounds up to 6
        float num2 = 5.9f; // Rounds up to 6
        float num3 = -5.9f; // Rounds up to -5 (less negative)
        int int1 = (int) Math.ceil(num1); // Becomes 6
        int int2 = (int) Math.ceil(num2); // Becomes 6
        int int3 = (int) Math.ceil(num3); // Becomes -5
        System.out.println("Original float: " + num1 + " -> Ceiled int: " + int1);
        System.out.println("Original float: " + num2 + " -> Ceiled int: " + int2);
        System.out.println("Original float: " + num3 + " -> Ceiled int: " + int3);
    }
}

Output:

Original float: 5.1 -> Ceiled int: 6
Original float: 5.9 -> Ceiled int: 6
Original float: -5.9 -> Ceiled int: -5

Important Considerations

Rounding Errors

Floating-point numbers (float and double) are not always represented perfectly in binary. This can lead to unexpected results.

// A classic example of a floating-point error
float f = 1.1f * 100; // You might expect 110.0, but it might be 109.999...
int i = (int) f; // This will result in 109, not 110
System.out.println(f); // Might print 109.99999...
System.out.println(i); // Prints 109

Solution: If precision is critical, especially for financial calculations, consider using BigDecimal. Or, add a small epsilon value before casting to ensure rounding works as expected.

// Safer way to round before casting
float f = 1.1f * 100;
int i = (int) (f + 0.5f); // Adding 0.5 before casting mimics Math.round()

Overflow

A float can represent a much larger range of numbers than an int. If you try to convert a float that is outside the range of an int (-2,147,483,648 to 2,147,483,647), the result will overflow.

float largeFloat = 3.4e38f; // A very large number
int largeInt = (int) largeFloat; // This will overflow!
System.out.println(largeFloat); // Prints 3.4028235E38
System.out.println(largeInt);   // Prints -2147483648 (Integer.MIN_VALUE)

Solution: Always check the bounds of your float before converting if there's any chance it could be out of the int range.

Which Method Should I Use?

  • Use (int) casting when you simply want to discard the decimal part and don't care about rounding (e.g., getting the integer part of a coordinate).
  • Use Math.round() when you want to get the closest integer value to the float (e.g., rounding a user's average score).
  • Use Math.floor() when you always need to round down (e.g., calculating how many full boxes you can pack).
  • Use Math.ceil() when you always need to round up (e.g., calculating how many trucks you need to ship all items, even if the last truck is not full).
分享:
扫描分享到社交APP
上一篇
下一篇