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
Release: 2024-12-05 03:05:10
Original
220 people have browsed it

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);
Copy after login

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

float percentage = ((float) totalOptCount) / totalRespCount;
Copy after login

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

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

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template