Reputation: 10531
float f = 0.564f;
System.out.println(String.format("Percent: %.3f%%", f));
This displays as below:
Percent: 0.564%
I want to display as 56.4% and I want to use String.format(). How to change this to achieve the effect?
Upvotes: 0
Views: 154
Reputation: 2408
The proper way is to calculate the percentage first from the proportion:
String.format("Percent: %.1f%%", 100 * f)
Note that your expected output only has 1 decimal. 3 decimals would display as
56.400%
. If you want that, don't change your format string.
Upvotes: 2
Reputation: 1879
You can simply do this with 1 decimal:
System.out.println(String.format("Percent: %.1f%%", (f*100)));
If you want to have it with 3 decimals
System.out.println(String.format("Percent: %.3f%%", (f*100)));
And so on
Upvotes: 2