Macros – How to Process Command Parameters into a Certain Number of Characters

macros

Currently, I’m in the process of writing a travel guide and I’d like to include general price information next to the locations and events, e.g.

$$$$ – Fancy Expensive Steakhouse

I figured that since I’d be doing this a lot it’d be a good idea to make a little command to insert an arbitrary number of dollar signs instead of individually escaping each dollar sign, but for the life of me I couldn’t figure it out.

Ideally, I’d want the command to go something like

\price{4}

To insert 4 dollar signs like in the above. I feel like I’m missing something simple, but after googling various variations of my question and looking into tex macros (unfortunately unfruitfully) I’m still at a loss. I’d also like to be able to format the dollar symbols (in gray for instance), but I feel like I can do that by defining an environment around the \price command once I get it working.

Any help or pointers to relative documentation would be greatly appreciated. Thanks!

Best Answer

It's better to separate \price and \pricesymbol.

\documentclass{article}
\usepackage{xcolor}

\NewDocumentCommand{\pricesymbol}{}{\textcolor{black!60}{\$}}

\ExplSyntaxOn

\NewDocumentCommand{\price}{m}
 {
  \prg_replicate:nn { #1 } { \pricesymbol }
 }

\ExplSyntaxOff

\begin{document}

\price{4} -- Fancy Expensive Steakhouse

\price{2} -- Pizza House (no pineapple)

\end{document}

enter image description here

You can even have fractional price symbols.

\documentclass{article}
\usepackage{xcolor}
\usepackage{trimclip}

\NewDocumentCommand{\pricesymbol}{}{\textcolor{black!60}{\$}}

\ExplSyntaxOn

\NewDocumentCommand{\price}{m}
 {
  \prg_replicate:nn { \fp_eval:n { trunc(#1,0) } } { \pricesymbol }
  \fp_compare:nT { #1 - trunc(#1,0) > 0 }
   {
    \clipbox{0~0~{\fp_eval:n { 1 - #1 + trunc(#1,0) }\width}~0} { \pricesymbol } \,
   }
 }

\ExplSyntaxOff

\begin{document}

\price{4} -- Fancy Expensive Steakhouse

\price{2} -- Pizza House (no pineapple)

\price{2.3} -- Pizza House (no pineapple)

\price{2.5} -- Pizza House (no pineapple)

\price{2.7} -- Pizza House (no pineapple)

\end{document}

enter image description here

Related Question