Reputation: 325
I have the following Java code:
public class Time {
private Main m;
private long st;
private long et;
public Time(Main m, long g){
this.m = m;
st = System.currentTimeMillis();
et = st+g;
}
public void update() {
long now = System.currentTimeMillis();
float per;
if (st >= et || now >= et) {
m.setPer(100);
return;
}
if (now <= st) {
m.setPer(000);
return;
}
per = (now - st) * 100 / (et - st);
System.out.println(per);
m.setPer(per);
}
}
which sets the percent of time out of the interval length has passed, which is used to render the same percentage of the border of a circle as the percentage of the interval.
My problem is that I require greater precision than is lent by the long type, because it is jumpy.
When I cast the variables to float or double, it overflows.
How can I get greater precision under these circumstances?
Upvotes: 0
Views: 347
Reputation: 46
The arithmatic needs to be done as a double. You may be able to modify the update function as follows to get the result you are after. Notice this line in particular:
per = (now - st) * 100.0 / (et - st);
The code below changes the variables used to from longs.
public void update() {
double now = (double)System.currentTimeMillis();
double per;
if (st >= et || now >= et) {
System.out.println ("st: " + st + ", et: " + et);
System.out.println(100);
return;
}
if (now <= st) {
System.out.println(000);
return;
}
per = (now - st) * 100.0 / (et - st);
System.out.println(per);
}
Upvotes: 1
Reputation: 7213
System.nanoTime() should be what you are looking for with nanotime precision.
Upvotes: 0