TeX - LaTeX Stack Exchange is a question and answer site for users of TeX, LaTeX, ConTeXt, and related typesetting systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have a custom macro like this that stores data:

\somecommand{some text}{234}

Inside the newcommand for this, I can access the second column of data using #2.

  • How can I obtain the first digit of that number? For e.g.:

\somecommand{some text}{3012} gives 3

\somecommand{some text}{21231} gives 2

\somecommand{some text}{9} gives 9

share|improve this question
What does \somecommand look like, since \somecommand does not have a #3 argument? – Werner Nov 28 '11 at 1:07
Oh, I made an error while writing it, I will fix that. – Village Nov 28 '11 at 1:11
up vote 11 down vote accepted

You could use \StrLeft from the xstring package:



\somecommand{some text}{3012}

\somecommand{some text}{21231}

\somecommand{some text}{9}

share|improve this answer

The usual approach using TeX programming would be


where \stop is 'something that will not appear in #2'.

share|improve this answer

A general solution without xstring (but tricky):


Joseph Wright pointed that it may fail if #2 is empty. However, it does work.

When we use \somecommand{foo}{}, we have


Then \somecommand{foo}{} expands to


And then, \helper\fi expands to


So we have




Anyway, Joseph's solution is better. My \somecommand is not expandable, it may fail in a \edef.

share|improve this answer
Runs away if #2 is completely empty. – Joseph Wright Nov 28 '11 at 7:08
@JosephWright: I'm sorry I didn't realized that case. However, \somecommand{foo}{} does works. \temp will be \fi (I don't know why) then \somecommand{foo}{} becomes \iffalse\temp and then \iffalse\fi. I;ll be glad if you can explain this. Maybe I'll post another question. – Leo Liu Nov 28 '11 at 9:06
OK, I understand it now. I'll add some explanations. – Leo Liu Nov 28 '11 at 9:13

You can simplify, if you wish using a macro with delimited parameters \def:

\def\somecommand #1|#2#3|{%
\somecommand Plenty of text|1234567|

I use | as a marker, but you can use anything you like. If there is no chance of a semicolon in the text, I would use a semicolon. This type of macro definition was quite a favourite with Knuth and there are many examples in the TeXbook. If the text is longer than a paragraph use \long\def.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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