Home >Java >javaTutorial >Why Does Integer Division in Java Return 0.0 and How Can I Get a Floating-Point Result?

Why Does Integer Division in Java Return 0.0 and How Can I Get a Floating-Point Result?

Linda Hamilton
Linda HamiltonOriginal
2024-12-08 21:07:10592browse

Why Does Integer Division in Java Return 0.0 and How Can I Get a Floating-Point Result?

Division of Integers in Java: Why It Returns 0.0

When performing division between two integers in Java, such as in the provided example where totalOptCount and totalRespCount are both integers, the result is automatically floored to an integer. This means any fractional part of the division is discarded. As a result, the percentage variable, which is declared as a float but initialized with the result of the division, will always be 0.0.

How to Obtain a Floating-Point Result

To obtain a floating-point result, at least one of the operands in the division must be casted to a floating-point type. In your case, you can cast totalOptCount to a float as follows:

float percentage = ((float) totalOptCount) / totalRespCount;

This will ensure that the division is performed in floating-point arithmetic, and the fractional part is preserved in the result.

Formatting the Percentage

To format the percentage variable into the "00.00" format and convert it into a string, you can use the String.format method:

String str = String.format("%2.02f", percentage);

The %2.02f placeholder specifies that the floating-point value should be formatted with a field width of 2 characters and a precision of 2 decimal places. This will result in a string with the percentage formatted as "00.00".

The above is the detailed content of Why Does Integer Division in Java Return 0.0 and How Can I Get a Floating-Point Result?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn