16

I prefer a large number be shown in three digit groups. For example 1234567 be shown like 1 234 567.

Is there a way to make this automatic in LaTeX such that wherever I insert 1234567, it is automatically shown as 1 234 567 in the output?

Mico
  • 506,678
Minimus Heximus
  • 715
  • 6
  • 19

3 Answers3

35

The packages numprint and siunitx can do this (here I show numprint)

\documentclass{article}

\usepackage{numprint}

\begin{document}
\numprint{1234567}

\numprint{123456789}
\end{document}

enter image description here

23

siunitx provides \num macro for such jobs.

\documentclass{article}
\usepackage{siunitx}
\begin{document}
  \num{1234567}
\end{document}

enter image description here

17

Here's a LuaLaTeX-based solution, which adds thinspaces automatically to the integer parts of numbers that contain between 5 and 12 digits.

Some comments:

  • Numbers with exactly four digits do not get a thinspace inserted after the first (left-most) digit, in keeping with the comment @egreg posted. If you do want a thinspace separator for numbers with exactly four digits, change the final string.gsub instruction line from

                text = string.gsub ( text , "(%d?%d%d)(%d%d%d)", "%1\\,%2" )
    

    to

                text = string.gsub ( text , "(%d?%d?%d)(%d%d%d)", "%1\\,%2" )
    
  • No thinspaces are inserted in the decimal portions of any long numbers; only the integer portions are processed.

  • The code keeps track of whether or not we are inside a verbatim or Verbatim environment. If we're inside such an environment, processing is suspended.

enter image description here

% !TEX TS-program = lualatex
\documentclass{article}

\usepackage{luacode}
\begin{luacode}
ok_to_process = true
function ez_read ( line )
  if string.find ( line , "\\begin{[vV]erbatim}" ) then
     ok_to_process = false
     return line
  elseif string.find ( line , "\\end{[vV]erbatim}" ) then
     ok_to_process = true
     return line
  else
    if ok_to_process then
      x = line:gsub ( "([%.]-)(%d+)", function ( back, text )
        if back ~= "" then
          return back..text
        end
        text = string.gsub ( text , "(%d?%d?%d)(%d%d%d)(%d%d%d)(%d%d%d)",
                                    "%1\\,%2\\,%3\\,%4" )
        text = string.gsub ( text , "(%d?%d?%d)(%d%d%d)(%d%d%d)",
                                    "%1\\,%2\\,%3" )
        text = string.gsub ( text , "(%d?%d%d)(%d%d%d)", "%1\\,%2" )
        return text
      end)
      return x
    end
  end
end
luatexbase.add_to_callback( "process_input_buffer", ez_read, "ez_read")
\end{luacode}

\begin{document}    
123456789012, 123456789, 123456, 12345

But: 1234 --- no thinspace after ``1''

123456.123456789, 0.12345, 123456
\end{document}
Mico
  • 506,678
  • Usually one doesn't want the separation in groups of four digits (except in tables where separation involves larger groups in the same column). – egreg Oct 24 '15 at 10:01