本文介紹了為什么Java中兩個整數相除返回0.0?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
為什么這總是返回值 0.0?我也想把它格式化成 00.00 格式并轉換成字符串?
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
推薦答案
因為到float的轉換發生在除法完成之后.你需要:
Because the conversion to float happens after the division has been done. You need:
float percentage = ((float) totalOptCount) / totalRespCount;
您應該能夠使用以下格式進行格式化:
You should be able to format using something like:
String str = String.format("%2.02f", percentage);
這篇關于為什么Java中兩個整數相除返回0.0?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!