int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
int totalOptCount = 500;
int totalRespCount=1500;
float percentage =(float)(totalOptCount/totalRespCount);
Why does this always return value 0.0? Also I want to format this into 00.00 format and convert into string?
因为转换为浮点数发生在除法完成之后。你需要:
float percentage = ((float) totalOptCount) / totalRespCount;
您应该能够使用以下内容进行格式化:
String str = String.format("%2.02f", percentage);
如果您使用int
值,则使用 adouble
可能是更好的选择,并且舍入误差更小。 float
可以int
无错误地表示高达约 1600 万的值。double
可以准确地表示所有int
值。
double percentage =(double) totalOptCount / totalRespCount;
百分比通常乘以 100,这意味着您可以放弃施法。
double percentage = 100.0 * totalOptCount / totalRespCount;
(totalOptCount/totalRespCount)
这里除数和除数都是类型int
,这意味着它们只允许整数值,并且此类等式的答案将始终是整数文字。
如果我打破它,它将如下所示
(double)(500/1500)
根据实际计算,500/1500 会给你 0.33333 但编译器会将其转换为整数文字,因为两个操作数都是 int 类型
(double)(0)
编译器得到一个指令来将该0
值转换为双倍,所以你得到了0.0
结果
0.0
然后您可以将结果更改为@Zach Janicki 建议的任何格式。
请记住,如果两个操作数的类型相同,那么结果也将具有相同的类型。
Java 中的整数除法(包括 long、short、byte、char、int)总是返回一个 int(或 long,如果其中一个参数为 long),向零舍入。您的转换发生在此计算之后。
(其他答案已经回答了格式问题 - 或者您也可以查看 java.text.NumberFormat,特别是 java.text.DecimalFormat。)
String.format("%2.02f", (float)totalOptCount/totalRespCount);
要格式化双精度并打印为百分比,您可以使用
System.out.println(new DecimalFormat("##.##").format(yourDouble) + "%"));