I want to highlight all the numbers appearing in an input code of a certain program by, for example, coloring them. By numbers I mean integer, rational and floating point numbers. I am trying with the listings page but with no success. I have noticed that specific numbers can be formatted with the morekeywords and alsoletter options on defining the language but I want to acomplish this task for any number.

For example, I would like the code


to appear with the three numbers with color green (or whatever). Is it possible to do this in an automatic way?


1 Answer 1


Similar to solutions in Visualization in LaTeX of hamming distance, and Problem with the alignment of characters, you could use the literate command to define a style that is to be applied to each digit. Below I included a color for the . but commented out the color for the ,.

enter image description here

As there might be a period used outside of a number context, I have defined different styles based on the assumption that any period used in a number will have a digit following it.


             {.0}{{\FormatDigit{.0}}}{2}% Following is to ensure that only periods
             {.1}{{\FormatDigit{.1}}}{2}% followed by a digit are changed.
             %{,}{{\FormatDigit{,}}{1}% depends if you want the "," in color
             {\ }{{ }}{1}% handle the space
   basicstyle=\ttfamily,%  Optional to use this

  • One caveat: This would format \FormattedNumber{a.vector(<stuff>)} by also making the period blue. It would be possible, but somewhat round-about to get that fixed using mathescape=true and then using \FormattedNumber{a$.$vector(<stuff>)}.
    – Werner
    Oct 20, 2011 at 17:07
  • @Werner: Excellent point. Have updated the solution to handle that case. Oct 20, 2011 at 17:19
  • That's perfect!!! You saved me a lot of time. Thank you!!! Oct 20, 2011 at 18:22
  • All replacements that include the comma should have 2 instead of 1 at the end. this defines the number of output characters and is important for the complicated spacing of listings.
    – stefanct
    Mar 29, 2014 at 0:45
  • @PeterGrill excellent solution! Only caveat for me is that it still highlights integers, even when they are commented. Is there a way to correct this?
    – han-tyumi
    Dec 16, 2015 at 15:35

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.