1

So I am loading a csv file that looks something like this:

est;dens;mwp
ols11;0.1;.
ols12;0.09;0.001

I want to use the following code to divide two numbers. I use the .csv in a table, but I also refer to them in the text, and would like this to be automated. But I get the following error from the code: Missing number, treated as zero. for the line \basiceval{\x/\y}. I am not very experienced with evaluating numbers in LaTex, so any help would be appreciated!

\documentclass{article}

\usepackage{datatool}
\DTLsetseparator{;}
\DTLloaddb{mun_reg}{63_mun_result.csv}
\def\basiceval#1{\the\numexpr#1\relax}

\begin{document}
\def\x{\DTLfetch{mun_reg}{est}{ols11}{dens}}
\def\y{\DTLfetch{mun_reg}{est}{ols12}{dens}}
\basiceval{\x/\y}

\end{document}

1 Answer 1

1

There are two issues with the approach in the question: first \numexpr performs integer division, so you can't use it for 0.1/0.09, and second the \DTLfetch statement is not expanded in the \def, so you essentially try to divide a (very complex) macro by another macro, instead of dividing two numbers as you expect.

To perform calculations on decimal numbers datatool has some built-in mathematical functions, among which \DTLdiv (for division). The input of these functions is supposed to be a macro holding a value, and the result is also stored in a macro. For storing database values in a macro you can use \DTLgetvalueforkey instead of \DTLfetch. Note that for \DTLgetvalueforkey the order of the column and row specification is different (first the column for which you want to find the value, then the reference column and row).

For more information on the mathematical functions you can read section 3 of the manual, specifically page 24 and further.

MWE:

\documentclass{article}
\usepackage{datatool}
\DTLsetseparator{;}
\DTLloaddb{mun_reg}{63_mun_result.csv}

\begin{document}
\DTLgetvalueforkey{\myx}{dens}{mun_reg}{est}{ols11}
\DTLgetvalueforkey{\myy}{dens}{mun_reg}{est}{ols12}
\DTLdiv{\mydiv}{\myx}{\myy}
Result: \mydiv
\end{document}
2
  • Ah! Thank you! I suspected that there should be a division in Datatools, but I am quite new to macros and that package, so I had some issues understanding the documentation properly. This worked like a charm, and I understand more how macros work! Thank you very much!
    – Karl
    Jan 20, 2021 at 17:37
  • 1
    I also wanted to specify what decimals I wanted. For anyone also reading this, I did this by adding \DTLround{\mydiv}{\mydiv}{2} below \DTLdiv{\mydiv}{\myx}{\myy}, giving 2 decimals!
    – Karl
    Jan 20, 2021 at 17:56

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .