https://kotlinlang.org logo
#getting-started
Title
# getting-started
a

Ayfri

03/11/2022, 4:34 AM
Is there a more efficient way than
round(number / length) * length
to round a number by a length ?
m

Michael de Kaste

03/11/2022, 8:44 AM
is it rounding for output only? Than I suggest using
Copy code
"%.${length}f".format(number)
otherwise, mathmatically theres is not really much you can do to round more efficiently
k

Klitos Kyriacou

03/11/2022, 9:20 AM
The print formatting is not equivalent to the OP's rounding (which means to round to the nearest multiple of
length
). I think, if
length
is an integer, you can probably make it slightly more efficient using just integer arithmetic, but it's probably not worth the effort.
a

Ayfri

03/11/2022, 11:38 AM
Yes it's integer, but it's an operation that will be used at least 300 times per second, it's for a Kotlin/JS game
k

Klitos Kyriacou

03/11/2022, 12:32 PM
If it's for JS, I wouldn't bother, as there is no integer type in Javascript; only Number.
t

Tim Oltjenbruns

03/11/2022, 6:34 PM
If you can guarantee length is a multiple of 2, you can use bitwise operators to round your number to a multiple of length
@Ayfri for example if you want to round by 8, shift right 3 and then shift left 3 (8 = 2^3)
That why for example, Minecraft, uses a lot of 8's and 16's as their grid size, because it makes the frequent rounding to snap to a grid much more efficient.
technically, if you’re going to shift right/left 3 you can just use bitwise & to delete the last 3 bits
For example, in JS
Copy code
const numberToRound = 15; 
const length = 8
const bitmask = Number.MAX_SAFE_INTEGER - length + 1;

console.log(numberToRound & bitmask);
But again, only works for multiples of 2
Make sure to test the performance though, I’m not sure if JavaScript’s representing all numbers in floating point makes this optimization useless or not. I know it works on platforms that have true integer types.
2 Views