Skip to content

PSA: Vim Modulo '%' Returns Negative Numbers!

-10 % 3 != -1

Surprise! Vim has the same modulo bug as Javascript. Some say it's not a bug, but if Ruby and Google Calculator is wrong, I don't want to be right.

  • Vim, :echo -10 % 3 returns -1
  • Javascript -10 % 3 returns -1
  • Ruby/IRB, -10 % 3 returns 2 -- my expectation is here

Solution

Add this function some where in your Vimscript and throw away %.

" ((n % m) + m) % m` or `((-10 % 3) + 3) % 3` returns `2`
function! s:mod(n,m)
  return ((a:n % a:m) + a:m) % a:m
endfunction

I hope this saves someone some time somewhere out there. It's an hour I'll never get back, but happy to give back.

References

Comments