16

I have implemented couple of macros that should remove commas from numbers. It's nasty dirty stuff, but it works when input is number:

\removecommas{12,34,56.7} % => 123456.7

But it stop working when the input is given by some command, such as:

\newcommand\mynumber{12,34,56.7}
\removecommas\mynumber

Why is this happening? How can I force TeX to expand \mynumber before commas? I've tried:

\expandafter\removecommas\mynumber

but that didn't seem to help.

migrated from stackoverflow.com Aug 28 '11 at 11:50

This question came from our site for professional and enthusiast programmers.

21

You are nearly there with

\expandafter\removecommas\mynumber

What is needed is a group:

\expandafter\removecommas\expandafter{\mynumber}

To understand why, you have to remember that TeX grabs arguments as tokens. Taking the example input, in the first case, you expand \mynumber to 12,34,56.7. TeX then grabs 1 as the argument to \removecommas, and unsurprisingly nothing actually happens. On the other hand, with the group in place all of 12,34,56.7 is grabbed by \removecommas, and the processing takes place as you want.

(Notice that we need two \expandafter primitives. The second one is needed to expand past {.)

5

If you need only up to one level expansion, this works:

\def\removecommas{\begingroup\catcode`,=9 \doremove}
\def\doremove#1{\scantokens\expandafter{#1\endinput}\endgroup}
4

The other answers explain the macro expansion. However, if all you want to do is to remove the commas in numbers you could use the numprint package with the following setup:

\documentclass{article}
\usepackage{numprint}

\makeatletter%
\renewcommand*\nprt@dotlist{.}% only . for decimal separator in input
\renewcommand*\nprt@ignorelist{,}% ignore , in input
\npdecimalsign{\ensuremath{.}}% use . as decimal output
\npthousandsep{}%
\makeatother%

\begin{document}
\numprint{12,34,56.7}
\end{document}

Your Answer

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