我有以下代码:
float fl = ((float)20701682/(float)20991474); 这就给了我fl = 0.9861948。
我想把0.9861948转换成2%,因为2%已经下载了。
我正在下载一个文件并计算进度。
任何帮助都是徒劳的。
发布于 2011-11-16 04:19:16
我猜你的意思是像这样
int percentage = (1 - fl) * 100;来计算百分比。
但对于fl = 0.9861948,这会产生1 (1.38052强制转换为整数)。
如果您希望使用2,则可以使用Math.ceil
int percentage = (int) Math.ceil((1 - fl) * 100); // gives 2发布于 2011-11-16 04:21:19
你在代码中有常量值,你应该用代表下载量和总大小的变量替换它们:
float downloaded = 50;
float total = 200;
float percent = (100 * downloaded) / total;
System.out.println(String.format("%.0f%%",percent));产出: 25%
发布于 2015-06-08 11:19:47
我在下面编写了两个方法,将浮点数转换为显示为百分比的字符串:
//without decimal digits
public static String toPercentage(float n){
return String.format("%.0f",n*100)+"%";
}
//accept a param to determine the numbers of decimal digits
public static String toPercentage(float n, int digits){
return String.format("%."+digits+"f",n*100)+"%";
}测试Case1:
public static void main(String[] args) {
float f = 1-0.9861948f;//your number,0.013805211
System.out.println("f="+f);//f=0.013805211
System.out.println(toPercentage(f));//1%
System.out.println(toPercentage(f,2));//1.38%
}测试Case2:
如果您想要2%,请尝试输入参数,如下所示:
float f = 1-0.9861948f;//your number,0.013805211
f= (float)(Math.ceil(f*100)/100);//f=0.02
System.out.println("f="+f);f=0.02
System.out.println(toPercentage(f));//2%
System.out.println(toPercentage(f,2));//2.00%https://stackoverflow.com/questions/8142573
复制相似问题