I have read this article NUM00-J. Detect or prevent integer overflow and this question How does Java handle integer underflows and overflows and how would you check for it?.
As you can see, there are many solutions to prevent integer overflow when multiplying an integer by an integer. But I wonder is there any solution to prevent integer overflow when multiplying an integer by float?
My current (silly) solution:
public static final int mulInt(int a, float b) {
double c = a * b;
return c > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int)c;
}
But it has a lot of problems:
- It can get the expected result when multiplying performs multiplication with both parameters having to be small numbers.
- When either parameter is large digits the result is bound to be incorrect (I know in part because of the floating-point data type).
- Suppose if the result of the calculation is even greater than the maximum value of double, it will be unstoppable and return a negative number.
So, what is the real solution to this problem?
Your answer will be very helpful, I will appreciate it!
UPDATE: There is another question here How can I check if multiplying two numbers in Java will cause an overflow? that is quite similar BUT it is about multiplying an integer by an integer instead of multiplying by a float.