5

I have a problem with rounding --- I have seen How do I get \pgfmathparse to create value rounded to one decimal place? but still I can't obtain the result I need.

See this MWE:

\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{pgf}
\usepackage{calc}
\usepackage{lmodern}
\usepackage{venturis}
\usepackage{librebaskerville}

\newlength\caph\newlength\xlen%
\newcommand*{\prlen}[1]{%
   % round to 1 digit:
    \pgfmathparse{round(10*#1)/10.0}%
    \pgfkeys{/pgf/number format/precision=1}
    \pgfmathresult
   % \pgfmathprintnumber[fixed, precision=1]{\pgfmathresult}
}
%
\newcommand{\showlengths}{%
\setlength{\caph}{\heightof{A}}%
\setlength{\xlen}{1ex}%
{\ttfamily
Caph: \prlen{\caph} \the\caph \par
X-He: \prlen{\xlen} \the\xlen \par
\medskip
}
}

\begin{document}

\librebaskerville\fontsize{100pt}{120pt}\selectfont
\showlengths

\fontfamily{yvtj}\fontsize{100pt}{120pt}\selectfont
\showlengths

\fontfamily{yvtd}\fontsize{100pt}{120pt}\selectfont
\showlengths

\fontfamily{lmr}\fontsize{100pt}{120pt}\selectfont
\showlengths

\end{document}

which results in:

output

...and you can see the loss of precision in the division by ten biting me sometime. If I change the definition of \prlen to use \pgfmathprintnumber, like this:

\newcommand*{\prlen}[1]{%
   % round to 1 digit:
    \pgfmathparse{round(10*#1)/10.0}%
    %\pgfkeys{/pgf/number format/precision=1}
    %\pgfmathresult
    \pgfmathprintnumber[fixed, precision=1]{\pgfmathresult}
}

I have this, which prints things in math font:

New output

Is there a way to have a correct rounding but using the normal font I am using outside, like in the first case?

1 Answer 1

7

The macro \pgfmathprintnumber uses math mode for this.

I suggest changing the definition of \prlen:

\usepackage{xparse}

\ExplSyntaxOn
\NewDocumentCommand{\prlen}{m}
 {
  \fp_eval:n { round(\dim_to_fp:n { #1 }, 1) }
 }
\ExplSyntaxOff

enter image description here

If you want one decimal digit even if zero, you can do

\usepackage{siunitx}
\ExplSyntaxOn
\NewDocumentCommand{\prlen}{m}{%
  \num[
    detect-all,
    round-integer-to-decimal,
    round-mode=places,
    round-precision=1,
  ]{\fp_eval:n { \dim_to_fp:n #1 }}
}
\ExplSyntaxOff

enter image description here

2
  • Thanks, almost perfect. If only it printed 53.0 instead of 53... ;-)
    – Rmano
    Apr 10, 2016 at 16:49
  • 1
    @Rmano Your wish is my command!
    – egreg
    Apr 10, 2016 at 22:04

You must log in to answer this question.

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