user697911
user697911

Reputation: 10531

How to display this as percent with 3 decimals in Java?

  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

Answers (2)

AlexR
AlexR

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

Mazz
Mazz

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

Related Questions