quwuwuza
quwuwuza

Reputation: 394

How do I format 2 long values into percentage formats?

Consider this situation.

I have 2 long variables a and b.
I'm trying to get percentage in these formats:

xx.x and 0.xx.

I've tried casting both to double and dividing but I'm not getting in the latter format.

Upvotes: 3

Views: 5343

Answers (1)

zakinster
zakinster

Reputation: 10688

Something like that ?

long a = 12, d = 34;
double ratio = a / (double) d;
DecimalFormat ratioFormat = new DecimalFormat("#.##");
DecimalFormat percentFormat= new DecimalFormat("#.#%");
System.out.println("ratio = " + ratioFormat.format(ratio));
System.out.println("percent = " + percentFormat.format(ratio));

Which outputs :

ratio = 0.35
percent = 35.3%

Upvotes: 5

Related Questions