How can I separate the digits of a long number in groups of custom length?

Here's a \groupify command:

\groupify[<sep>]{<n>}{<tokens>}

which will separate the <tokens> in groups of <n> items (starting form the left) and will insert <sep> between each pair of groups. The default <sep> is \,\allowbreak (a thin space which allows a line break).

\documentclass{article}
\usepackage{xparse}
\ExplSyntaxOn
\NewExpandableDocumentCommand \groupify { O{\,\allowbreak} m m }
  { \jakob_groupify:nnn {#1} {#2} {#3} }
\cs_new:Npn \jakob_groupify:nnn #1 #2 #3
  { \__jakob_groupify_loop:nnw { 1 } {#2} #3 \q_recursion_tail {#1} \q_recursion_stop }
\cs_new:Npn \__jakob_groupify_loop:nnw #1 #2 #3
  {
    \quark_if_recursion_tail_stop:n {#3}
    \exp_not:n {#3}
    \int_compare:nNnTF {#1} = {#2}
      { \__jakob_groupify_sep:n }
      { \exp_args:Nf \__jakob_groupify_loop:nnw { \int_eval:n { #1+1 } } }
          {#2}
  }
\cs_new:Npn \__jakob_groupify_sep:n #1 #2 \q_recursion_tail #3
  {
    \tl_if_empty:nF {#2} { \exp_not:n {#3} }
    \__jakob_groupify_loop:nnw { 1 } {#1}
    #2 \q_recursion_tail {#3}
  }
\ExplSyntaxOff
\begin{document}
\groupify{3}{01234567890123456789012345678901234567890123456789}

\groupify[ X ]{5}{01234567890123456789012345678901234567890123456789}
\end{document}

Here's a LuaLaTeX-based solution. It consists of a Lua function called groupnum which does the actual work and a LaTeX macro called \groupnum, which takes two arguments. The first is optional and sets the grouping length; the default length is 4. The second is the number that's supposed to be grouped.

enter image description here

% !TEX TS-program = lualatex
\documentclass{article}
\usepackage{luacode}
\begin{luacode}
function groupnum ( s , n )
   while #s > n do
      tex.sprint ( s:sub(1,n) .. "\\mkern3mu\\allowbreak")
      s = s:sub(n+1) 
   end
   tex.sprint ( s )
end   
\end{luacode}
%% LaTeX utility macro:
\newcommand\groupnum[2][4]{\directlua{groupnum("#2",#1)}}

\begin{document}
\raggedright
$\groupnum{123456789012345}$

$\groupnum[5]{123456789012345}$

$\groupnum[7]{1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890}$
\end{document}