Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java how to make user friendly percentage output from float number

Tags:

java

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.

like image 980
Erik Avatar asked Nov 15 '11 20:11

Erik


2 Answers

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%
like image 195
JaskeyLam Avatar answered Oct 03 '22 23:10

JaskeyLam


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%

like image 27
yurib Avatar answered Oct 03 '22 21:10

yurib