Let us say that I have a function, in which I give a number plus a unit. I would like to get only the number, is it possible ?

Here is a MWE:


\newcommand{\cmd}[1]{#1} % change here to capture only the number.  
    \cmd{12pt} % print 12pt while I would get only 12, in a generic case.
  • 1
    \documentclass{article} \def\cmd#1pt{#1} \begin{document} \cmd12pt \end{document} – marmot Apr 1 at 18:55
  • @marmot - That'll work for pt as the unit, but for em, mm, km, etc. :-) – Mico Apr 1 at 20:24
  • @Mico Yes, I know. But it does answer the question. – marmot Apr 1 at 20:25

pgf does that without the need to invoke external programs and converts the units into points.


    \cmd{12pt} \cmd{1cm} 

enter image description here

Note that if you're bugged by the .0: this can easily be removed with \pgfmathprintnumber[<your number format here>]{pgfmathresult} if you choose a number format that you like.


Assuming the unit consists of two characters, you can do it in an expandable way:



  \tl_range:nnn { #1 } { 1 } { -3 } % from the first to the last but two character



\getnumber{12pt}, $\getnumber{-47km}$, \getnumber{+5.7in}, \getnumber{3,14159CM}


enter image description here

  • Could \getnumber be generalized, say by taking an integer as an optional argument (with the default value of the optional argument set to 2), to handle cases of units which contain a number of characters not equal to 2? E.g., \getnumber[3]{5.678mol} or \getnumber[1]{1.23m}. – Mico Apr 2 at 6:56

Here's a LuaLaTeX-based solution. It sets up a LaTeX macro called \cmd -- a "wrapper" -- that invokes a Lua function that does all of the work. The Lua function expects its argument to consist of two parts: the first part is numeric, i.e., consists of the digits 0 thru 9, plus possibly the characters ,, ., -, and +; the part second is alphabetic, i.e., uppercase and lowercase letters, plus possibly whitespace.

Per your typesetting objective, the function returns just the numeric, part. If the argument of \cmd does not start with a numeric component, the prefix part is discarded as well. E.g., the output of \arg{XX55km} is 55, and the output of \cmd{km} is blank (empty).

enter image description here

% !TEX TS-program = lualatex
\usepackage{luacode} % for 'luacode' environment
function get_num ( s )
  tex.sprint ( ( s:gsub ( "([%d%.%,%-%+]*)([%a%s]*)" , "%1" ) ) )
\newcommand\cmd[1]{\directlua{get_num("#1")}}  % "wrapper" macro

\cmd{12pt}, $\cmd{-47km}$, \cmd{+5.7in}, \cmd{3,14159CM}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.