问题
What is the most efficient way (in Java) to round an integer in 30 increments. My output will be an Integer:
Here is my code that returns minutes in integer.
long different = endTime.getTime() - startTime.getTime();
int idiff = TimeUnit.MILLISECONDS.toMinutes(different) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(different));
Now I want to round up this integer. For example:
Any number <= 30 = round up to 30:
Any number between 31 to 60 = round up to 60
Any number between 61 to 90 = round up to 90
Any number between 91 to 120 = round up to 120
Any number between 121 to 150 = round up to 150
回答1:
Add one less than the group you want, then divide and multiple.. so for 30 do
((value + 29) / 30) * 30
This assumes you want 0 to stay at 0, 30 to stay at 30...
回答2:
This should work :
x = ((x+30)/30) * 30;
Examples :
((15+30)/30)*30 == (45/30)*30 == 1*30 == 30
((30+30)/30)*30 == (60/30)*30 == 2*30 == 60
((47+30)/30)*30 == (77/30)*30 == 2*30 == 60
...
EDIT :
After the OP changed the requirements (30 should stay 30) :
x = ((x+29)/30) * 30;
Examples :
((15+29)/30)*30 == (44/30)*30 == 1*30 == 30
((30+29)/30)*30 == (59/30)*30 == 1*30 == 30
((47+29)/30)*30 == (76/30)*30 == 2*30 == 60
...
来源:https://stackoverflow.com/questions/27082097/round-up-in-30-min-nearest-half-hour-increments