In java what happens if I cast a negative float -237.485 to an int vs a positive float
- User
In java what happens if I cast a negative float -237.485 to an int vs a positive float
- Assistant
In Java, when you cast a floating-point number (such as a
floatordouble) to an integer (int), the fractional part is truncated, not rounded. This is true for both positive and negative numbers.Here’s what happens when you cast a negative float and a positive float to an integer:
Negative Float
Let's take your example of a negative float:
float negativeFloat = -237.485f; int negativeInt = (int) negativeFloat; System.out.println(negativeInt);When you cast
-237.485ftoint, the fractional part.485is truncated, not rounded. Therefore,negativeIntwill be-237.Positive Float
Now consider a positive float:
float positiveFloat = 237.485f; int positiveInt = (int) positiveFloat; System.out.println(positiveInt);When you cast
237.485ftoint, the fractional part.485is truncated, not rounded. Therefore,positiveIntwill be237.