I have the following code:
float fl = ((float)20701682/(float)20991474);
And that gives me fl = 0.9861948
.
I would like to convert 0.9861948
to 2%
since 2%
has been downloaded.
I'm downloading a file and calculating progress.
Any help would be grate.
I wrote two methods below to convert a float number to a string displayed as percentage:
//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)+"%";
}
Test 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%
}
Test Case2:
If you want 2% instead, try to input a param like this:
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%
you have constant values in the code, you should replace them with the variables representing the amount downloaded and the total size:
float downloaded = 50;
float total = 200;
float percent = (100 * downloaded) / total;
System.out.println(String.format("%.0f%%",percent));
output: 25%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With