[Tex/LaTex] How to round number to two digits after the decimal place and have a comma separator

calculationsformatting

I have the following function:

% Formats inputed number with 2 digits after the decimal place
\newcommand*{\formatNumber}[1]{\FPround{\cost}{#1}{2}\cost} %

\cost goes through some calculations before this.

Is it possible to change this so that it rounds to 2 digits after the decimal place and uses a comma as separator?

Best Answer

expl3 provides a host of formatting options via siunitx. The following should suit your needs:

\documentclass{article}
\usepackage{siunitx}
\ExplSyntaxOn
  \cs_new_eq:NN \calc \fp_eval:n
\ExplSyntaxOff

\newcommand*{\formatNumber}[2][]{\num[%
  round-mode=places,% Round output to specified number of places
  round-precision=3,% Round-precision is 3
  output-decimal-marker={,},% Use , as decimal marker
  #1% Other options
  ]{\calc{#2}}}

\begin{document}

\formatNumber{2*3/5+pi}% 4.342

\formatNumber[round-precision=1]{2*3/5+pi}% 4.3

\newcommand{\cost}{20}

\formatNumber{\cost+pi}% 23.142

\end{document}

4,342
4,3
23,142

Options can be set globally (via \sisetup{<options>}) or locally, as is done inside the options for \num[<options>].

Related Question