为了演示,这里有一个 MWE:
\documentclass[a4paper,titlepage]{article}
\usepackage{pgf}
\usepackage{siunitx}
\begin{document}
\pgfmathparse{1 + 1}
\pgfmathprintnumberto{\pgfmathresult}{\calcResult}
% Both this line
\pgfmathparse{\calcResult + 1}
% and this one
\SI{\calcResult}{\cm}
% do not work.
\end{document}
我看到的错误是:
! Package PGF Math Error: Unknown operator `$' or `$2' (in '$2$+ 1').
! siunitx error: "invalid-token-in-number"
!
! Invalid token '$' in numerical input.
! siunitx error: "invalid-number"
!
! Invalid numerical input '$2$'.
!
! See the siunitx documentation for further information.
答案1
\pgfmathprintnumberto{2}{\calcResult}
结果为$2$
。您可以\pgfmathsetmacro{\calcResult}{1+1}
直接使用。要将数字四舍五入为整数,您可以int
像下面这样使用\pgfmathsetmacro{\calcResult}{int(1+1)}
\documentclass[a4paper,titlepage]{article}
\usepackage{pgf}
\usepackage{siunitx}
\begin{document}
\pgfmathsetmacro{\calcResult}{int(1+1)}
\pgfmathprintnumber{\calcResult}
% Both this line
\pgfmathparse{\calcResult + 1}
\pgfmathresult
% and this one
\SI{\calcResult}{\cm}
% do not work.
\end{document}
答案2
Harish 的回答是正确的,但另一种方法是使用 LaTeX3 FPU 来完成工作
\documentclass[a4paper,titlepage]{article}
\usepackage{siunitx}
\usepackage{expl3}
\ExplSyntaxOn
\cs_new_eq:NN \fpeval \fp_eval:n
\ExplSyntaxOff
\begin{document}
\SI{\fpeval{1 + 1}}{\cm}
\SI[round-integer-to-decimal, round-mode = places, round-precision = 1]%
{\fpeval{1 + 1}}{\cm}
\end{document}