Returning the nearest multiple value of a number

前端 未结 6 1620
灰色年华
灰色年华 2020-11-29 08:33

I need a function by which I will be able to convert a number to a nearest value of a given multiple.

Eg i want an array of number to be set to the neareast multiple

6条回答
  •  情歌与酒
    2020-11-29 09:36

    16*((n+8)/16) is the formula you want if, in particular, you want to convert 8 to 16 (it's equally close to 0 as to 16, so it's impossible to decide how to convert it based exclusively on the "nearest multiple" concept, you have to decide!-), and of course consistently 24 to 32, 40 to 48, and so forth. Use +7 in lieu of +8 if you'd rather convert 8 to 0 rather than to 16 (and consistently 24 to 16, and so forth).

    To use a generic X in lieu of the hardcoded 16, then the formula is X*((n+X/2)/X) (with the same proviso as in the above paragraph if X is even).

    Edit: no need to mess around with floating point numbers as other answers suggest, but you do need to multiply back by X (which I had erroneously omitted).

提交回复
热议问题