[Tex/LaTex] How to format a number with a certain precision

formatting

How do I change the precision of a number? The below example defines \mynum as a number with a large amount of digits. Most times when I use \mynum in the text I want it to be displayed exactly as defined, however I may sometimes wish to display it with 4 digits, so that in this example it would display as 12.35.

Is there a package or pre-existing latex function to do this? Most stuff I can find about altering number precision refers to tables and column formatting, which doesn't apply to single numbers in text.

\documentclass{article}
\newcommand{\mynum}{12.34567890}
\begin{document}
\mynum
\end{document}

I'm thinking something along the lines of this pseudo-code:

\round{4}{\mynum}    % not real code

Best Answer

Thanks to @moewe and @Steven B. Segletes for the package suggestions and working examples. This is the solution I was able to put together.

Essentially, I was able to use the \num macro provided in the siunitx package along with some appropriate optional arguments to round numbers to whatever level of precision I liked. There are two ways I could go about this:

  • Use round-mode=places,round-precision=2 to round to 2 decimal places
  • Or use round-mode=figures,round-precision=4 to round to 4 significant figures.

Both methods change 12.34567890 to 12.35. My code is below, and also includes a macro in the form of the pseudo-code I wrote in my question.

\documentclass{article}
\usepackage{siunitx}
\newcommand{\mynum}{12.34567890}
\newcommand{\round}[2]{\num[round-mode=places,round-precision=#1]{#2}}

\begin{document}

\mynum

\round{2}{\mynum}

\num[round-mode=figures,round-precision=4]{\mynum}

\end{document}

The output of this code is:

12.34567890
12.35
12.35
Related Question