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;
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%
source share