Java, how to make a convenient percentage output from a float

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% was loaded.
I upload a file and count the progress.

Any help would be resolved.

+6
source share
9 answers

I suppose you mean something like

 int percentage = (1 - fl) * 100; 

to calculate the percentage.

But for fl = 0.9861948 this gives 1 ( 1.38052 casted to int).

If you want 2 instead, you can use Math.ceil :

 int percentage = (int) Math.ceil((1 - fl) * 100); // gives 2 
+13
source

you have constant values ​​in the code, you should replace them with variables representing the loaded amount and total size:

  float downloaded = 50; float total = 200; float percent = (100 * downloaded) / total; System.out.println(String.format("%.0f%%",percent)); 

Yield: 25%

+16
source

I wrote two methods below to convert a floating point number to a string displayed as a 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 entering this parameter:

  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% 
+3
source

When you print a float, just say the string conversion just to prevent any / all / trailing digits:

System.out.printf("We have downloaded: %.0f %%%n", (1-fl) * 100);

But I'm not sure why you would like to round from 1.4% to 2%. If you really want this to be much more complicated, because there really was no good reason.

+1
source

How about (1.0 -fl) * 100?

Convert this to an integer and you won't have a problem.

+1
source

Since the percentage means β€œper 100”, perhaps you could have a few fl per 100. Since for some reason you want 0.98 to mean 2%, then you subtract the result from 100.

0
source

You need something like:

 float allSize = ...; float downloaded = ...; int percent = (allSize - downloaded/100 * 100.0)/allSize (downloaded/100 * 100.0) - used for make two digit of fractional part; 
0
source

After applying the logic ((1-fl) * 100) you can use DecimalFormat or String.format () .

0
source
 float fl = ((float)20701682 / (float)20991474)*100; int pct = 100 - Math.floor(fl) 
0
source

Source: https://habr.com/ru/post/901555/


All Articles