Problems with numbers (result of calculations) alignment using siunitx package inside tabular environment

Use the full power of expl3; the \KelvinToCelsius command must be expandable and you can have it even with an optional argument.

Using \fpeval frees you from fp.

\documentclass{article}
\usepackage{siunitx,xfp}
\usepackage{booktabs}

% #1: decimal places (default=2), #2: value
\NewExpandableDocumentCommand{\KelvinToCelsius}{O{2}m}{%
  \fpeval{round(#2-273.15,#1)}%
}

\begin{document}

\begin{tabular}{
  S[table-format=5.2]
  S[table-format=5.2]
}
\toprule
{\si{\kelvin}} & {\si{\celsius}} \\
\midrule
   10.3  & \KelvinToCelsius{10.3}     \\
  200.34 & \KelvinToCelsius{200.34}   \\
  500.26 & \KelvinToCelsius{500.26}   \\
 1200.5  & \KelvinToCelsius[1]{1200.5}\\
12345    & \KelvinToCelsius[0]{12345} \\
\bottomrule
\end{tabular}

\end{document}

enter image description here


The commands must be expandable so that siunitx sees "pure numbers". Better use the xfp package for the calculations and avoid optional arguments.

\documentclass{article}
\usepackage{siunitx}
\usepackage{xfp}
\usepackage{booktabs}

% #1: decimal places (default=2), #2: value
\newcommand*{\KelvinToCelsius}[1]{% no optional argument
    \fpeval{round((#1-273.15)/2,2)}%    
}

\begin{document}
    \begin{tabular}{S S}
        \toprule
        \si{\kelvin} & \si{\celsius} \\
        \midrule
           10.3  & \KelvinToCelsius{10.3}     \\
          200.34 & \KelvinToCelsius{200.34}   \\
          500.26 & \KelvinToCelsius{500.26}   \\
        %1200.5  & {\KelvinToCelsius[1]{1200.5}}\\
        %12345    & {\KelvinToCelsius[0]{12345}} \\
        \bottomrule
    \end{tabular}
\end{document}

enter image description here

Tags:

Tables

Siunitx