将 LaTeX 计数器与真实值相乘

将 LaTeX 计数器与真实值相乘

假设我想在 LaTeX 中创建发票。因此,我通过宏列出一些项目。宏将触发特定于项目的计数器。最后,我希望将该计数器的实际值(在我的情况下为整数)与项目的价格(即实际值)相乘。

我尝试了几次,但都失败了。在 LaTeX 中将 (整数) 计数器与 (实数) 宏相乘的最佳方法是什么?

这是我的 MWE,用来展示我的尝试。

\documentclass{scrartcl}

\usepackage[english]{babel}
\usepackage[T1]{fontenc}
\usepackage{calc}

%% Define the (integer) counter
\newcounter{quantitya}
%% ...  and set it to some arbitrary value, just for demonstration
%% purposes 
\setcounter{quantitya}{9}

%% Define the value of the price (as real number, of course)
\def\price{123.45}
% \newcommand{\price}{123.45}

\begin{document}
%% Increase the counter (this will later be executed from a more
%% complex macro ...)
\stepcounter{quantitya}
%% Calculate the total costs.  
\thequantitya{} pieces, each worth \price, cost in total
%% List of unsuccessful ideas:
% \price*\value{quantitya}                   % comipling error: Missing number
% \real{\price*\thequantitya}                % prints: 123.45*10 :-(
% \price*\thequantitya                       % same as above
\real{\price}*\thequantitya.                 % same as above
% \real{\price}*\value{quantitya}            % compiling error
but I expect a value of 1234.50.
\end{document}

在最佳情况下,结果将产生以下输出: 整数与实数相乘失败的结果

答案1

在此处输入图片描述

\fpeval采用较新的格式(或使用xfp较旧格式的包)

\documentclass{scrartcl}

\usepackage[english]{babel}
\usepackage[T1]{fontenc}
\usepackage{calc}

%% Define the (integer) counter
\newcounter{quantitya}
%% ...  and set it to some arbitrary value, just for demonstration
%% purposes 
\setcounter{quantitya}{9}

%% Define the value of the price (as real number, of course)
\def\price{123.45}
% \newcommand{\price}{123.45}

\begin{document}
%% Increase the counter (this will later be executed from a more
%% complex macro ...)
\stepcounter{quantitya}
%% Calculate the total costs.  
\thequantitya{} pieces, each worth \price, cost in total
\fpeval{\price*\thequantitya} or
\fpeval{trunc(\price*\thequantitya)}.%
\fpeval{trunc(100*(\price*\thequantitya-trunc(\price*\thequantitya)))}.
 

But I expect a value of 1234.50.
\end{document}

相关内容