我正在尝试将 SI 单位存储在变量中,以便我可以对数字进行数学运算,然后根据我们学校的工程师科学符号使用正确的前缀和指数显示它。我偶然发现了一个可以轻松存储这些的代码,但由于某种原因,当我将 SIsetup exponent-to-prefix 设置为 true 时,它会失败。有什么办法可以解决这个问题吗?
\documentclass{article}
\usepackage[per-mode=fraction]{siunitx} % also loads xparse and expl3
\sisetup
{
exponent-to-prefix = true ,
round-mode = figures ,
round-precision = 3 ,
scientific-notation = engineering,
}
\ExplSyntaxOn
\NewDocumentCommand{\setvariable}{mmm}
{
\prop_gclear_new:c { g_giacomo_var_#1_prop }
\prop_gput:cnn { g_giacomo_var_#1_prop } { value } { #2 }
\prop_gput:cnn { g_giacomo_var_#1_prop } { unit } { #3 }
}
\NewDocumentCommand{\printvariable}{sm}
{
\IfBooleanTF{#1}
{
\num { \__giacomo_get:nn { #2 } { value } }
}
{
\SI { \__giacomo_get:nn { #2 } { value } }
{ \__giacomo_get:nn { #2 } { unit } }
}
}
% syntactic sugar
\DeclareExpandableDocumentCommand{\getvalue}{m}
{
\__giacomo_get:nn { #1 } { value }
}
\cs_new:Npn \__giacomo_get:nn #1 #2
{
\prop_item:cn { g_giacomo_var_#1_prop } { #2 }
}
\cs_set_eq:NN \fpeval \fp_eval:n
\ExplSyntaxOff
\setvariable{Length}{800000}{\metre}
\begin{document}
\SI{800000}{\metre}
\printvariable{Length}
\end{document}
答案1
当exponent-to-prefix
设置为 true 时,代码会进入无限循环。
解决方法:在看到第二个参数之前将\SI
其完全展开。
\documentclass{article}
\usepackage[per-mode=fraction]{siunitx} % also loads xparse and expl3
\sisetup
{
exponent-to-prefix = true ,
round-mode = figures ,
round-precision = 3 ,
scientific-notation = engineering,
}
\ExplSyntaxOn
\NewDocumentCommand{\setvariable}{mmm}
{
\prop_gclear_new:c { g_giacomo_var_#1_prop }
\prop_gput:cnn { g_giacomo_var_#1_prop } { value } { #2 }
\prop_gput:cnn { g_giacomo_var_#1_prop } { unit } { #3 }
}
\NewDocumentCommand{\printvariable}{sm}
{
\IfBooleanTF{#1}
{
\num { \__giacomo_get:nn { #2 } { value } }
}
{
\exp_args:Nnx \SI { \__giacomo_get:nn { #2 } { value } }
{ \__giacomo_get:nn { #2 } { unit } }
}
}
% syntactic sugar
\DeclareExpandableDocumentCommand{\getvalue}{m}
{
\__giacomo_get:nn { #1 } { value }
}
\cs_new:Npn \__giacomo_get:nn #1 #2
{
\prop_item:cn { g_giacomo_var_#1_prop } { #2 }
}
\cs_set_eq:NN \fpeval \fp_eval:n
\ExplSyntaxOff
\setvariable{Length}{800000}{\metre}
\begin{document}
\SI{800000}{\metre}
\printvariable{Length}
\printvariable*{Length}
\end{document}