Veer
Veer

Reputation: 53

How to convert percentage of minutes in java

I want to calculate percentage of minutes in java. For eg: 10% of 3 minutes in 30 seconds.

Below is my code. I have a variable t which has time in minutes. I want to calculate 10% of time t and convert that to milliseconds. How can i do that? assmt_time10per is wrongly set to 0

int t = 3; // TIME IN MINUTES
long assmt_time = TimeUnit.MINUTES.toMillis(t);
long assmt_time10per = (t * 10) / 100;

Upvotes: 2

Views: 1115

Answers (2)

tinstaafl
tinstaafl

Reputation: 6948

I think maybe you're making it more complicated then necessary.

double percent=10;
int tm = 3;
double seconds = (tm * 60) / percent;

This will give you the percentage in seconds.

Upvotes: 0

Bentaye
Bentaye

Reputation: 9766

For 10%, convert your time in milliseconds and divide by 10.

Your error is here (you divide the time in minutes)

assmt_time10per = (t * 10) / 100;

It should be (you divide the time in milliseconds you just calculated)

assmt_time10per = (assmt_time * 10) / 100;

Also, when you divide 2 ints, you get an int as a result, here 3 by 10 is 0.3, it returns 0. If you want 0.3, you need to use doubles and set to a double, ie double d = (double)t / 10d;, this would set d to 0.3

Here is working code for x percents

int x = 10; // desired percentage
int t = 3; // time in minutes
long assmt_time = TimeUnit.MINUTES.toMillis(t);
long assmt_time10per = (assmt_time * x) / 100;
System.out.println(assmt_time10per);

Outputs 18000

Upvotes: 4

Related Questions