开发者

Ensure a number is a factor of another number

I need to ensure that values passed to one of my classes fit onto a grid with cells of 4px

So if 16 gets passed

16%4==0 //this is fine

however

17%4==1 //not ok

I need the program to convert the value to fit on the grid, so in the last case 17 would be converted to 16 (round down), if it were 19 it would get converted to 20 (round up) etc.

So is there a library that will do 开发者_StackOverflow社区this for me?


I think this does what you want, including the rounding up part.

int gridVal = (((int) val + 2) / 4) * 4

Edit for completeness:

If you want to round 18 down, then use this statment.

int gridVal = (((int) val + 1) / 4) * 4

If you want to deal with negative values as well, then you need a conditional.

int gridVal = ((val >= 0 ? (int) val + 2 : (int) val - 2) / 4) * 4

Edit for variable (even) grid size:

int halfGrid = gridSize / 2;
int gridVal = ((val >= 0 ? (int) val + halfGrid : (int) val - halfGrid) / gridSize) * gridSize;


Try something like

Devide by the number, then Round and multiply by the number.

Something like

val = Round(val / 4) * 4


Does this work for you?

val = val - (val % 4)

Now with rounding

val = Round(val / 4) * 4
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜