Round up in 30 min (nearest half-hour) increments:

孤人 提交于 2019-12-19 12:02:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!