PSA: Vim Modulo '%' Returns Negative Numbers!

written in vim

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 %.

1
2
3
4
" ((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