Reputation: 263
I have a vector:
p[0]=0.40816269
p[1]=0.37576407
p[2]=0.16324950
p[3]=0.05282373
I need to print the values of the vector as percentage with 4 decimals. I tried:
for(int i=0; i<p.length;i++)
{
System.out.printf("Criterion "+i+" has the weigth=%.4f \n" , p[i]*100);
}
which gives me:
Criterion 0 has the weigth=40.8163, .....
but I want to print:
Criterion 0 has the weigth=40.8163 %, .....
I cannot add the symbol "%" in the end of each row. If I try:
System.out.printf("Criterion "+i+" has the weigth=%.4f %\n" , p[i]*100);
or:
System.out.printf("Criterion "+i+" has the weigth=%.4f "+"%\n" , p[i]*100);
program throws an exception. Thank you in advance!
Upvotes: 2
Views: 941
Reputation: 30436
Why not just do this:
System.out.printf("Criterion %d has the weigth=%.4f%%\n", i, p[i]*100)
If you are going to use printf, then use it all the way :)
Upvotes: 2
Reputation: 32973
As the others said, but why not
System.out.printf("Criterion %d has the weight=%.4f%%\n" , i, p[i]*100);
It's a bit odd to use printf to format the float, but not for i..
Upvotes: 1
Reputation: 179552
Use %%
to print out a percent sign:
System.out.printf("Criterion "+i+" has the weight=%.4f%%\n" , p[i]*100);
Upvotes: 2
Reputation: 143906
You need to escapee the %
with %%
:
System.out.printf("Criterion "+i+" has the weigth=%.4f %%\n" , p[i]*100);
For more information, see the java.util.Formatter conversions spec
Upvotes: 5