Home >Java >javaTutorial >Why Does Integer Division in Java Result in 0.0, and How Can I Fix It?

Why Does Integer Division in Java Result in 0.0, and How Can I Fix It?

DDD
DDDOriginal
2024-12-05 03:05:10213browse

Why Does Integer Division in Java Result in 0.0, and How Can I Fix It?

Division of Integers Coerced to 0.0 in Java

When dividing two integers in Java, the result is cast to an integer, leading to the conversion of the result to 0.0 if both integers are positive. To resolve this issue, consider converting one or both integers to a floating-point type before performing the division.

In your specific code:

int totalOptCount = 500;
int totalRespCount=1500; 
float percentage =(float)(totalOptCount/totalRespCount);

To obtain the correct result, you should explicitly cast one of the operands to a float:

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

Optionally, you may format the result to the desired precision and convert it to a string:

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

The above is the detailed content of Why Does Integer Division in Java Result in 0.0, and How Can I Fix It?. 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