2

I need to define a Roundup function that is "defined as the smallest number, specified to one decimal place, that is equal to or higher than its input." For example, Round up (4.02) is 4.1; and Round up (4.00) is 4.0.

So far I've come up with this MWE, which nearly does the job :

\documentclass{article}
\usepackage{pgfmath}

\newcommand{\roundup}[1]{%
    \pgfmathparse{(ceil(#1*10)/10}%
    \pgfmathprintnumberto[precision=1,fixed]{\pgfmathresult}{\roundednumber}
    \roundednumber%
}%


\begin{document}

roundup(4.02) = \roundup{4.02} \qquad (should be 4.1)

roundup(4.0) = \roundup{4.0} \qquad (should be 4.0)

roundup(-0.27) = \roundup{-0.27} \qquad (should be -0.2)

\textbf{Problem : }

roundup(-0.2) = \roundup{-0.2}\qquad (should be -0.2)

\textbf{Reason}

\pgfmathparse{ceil(-2)}\pgfmathresult \qquad(this is OK)

\pgfmathparse{ceil(-0.2*10)}\pgfmathresult \qquad(\textbf{this is KO})

\end{document}

However, sometimes it poses problem.

MWE output

In the end, it boils down to the ceil function, and how pgfmath handles decimal numbers.

How can I right this behavior ?

1 Answer 1

1

You can use expl3 and its floating point module.

\documentclass{article}

\ExplSyntaxOn

\NewExpandableDocumentCommand{\roundup}{m}
 {
  \fp_eval:n { ceil(#1,1) }
  \fp_compare:nT { ceil(#1,1)=ceil(#1,0) } {.0}
 }

\ExplSyntaxOff

\begin{document}

roundup(4.02) = \roundup{4.02} \qquad (should be 4.1)

roundup(4.0) = \roundup{4.0} \qquad (should be 4.0)

roundup(3.91) = \roundup{3.91} \qquad (should be 4.0)

roundup(-0.27) = \roundup{-0.27} \qquad (should be -0.2)

roundup(-0.2) = \roundup{-0.2}\qquad (should be -0.2)

\end{document}

The \fp_compare:nT bit is for adding a trailing .0 which \fp_eval:n wouldn't.

enter image description here

Explanation: ceil(<expression>,<digits>) evaluates the ceiling with <digits> decimal places; ceil(<expression>,0) is equivalent to ceil(<expression>).

2
  • Thanks :) Any luck on getting this solved with pgfmath ?
    – 3isenHeim
    Commented Sep 15, 2021 at 6:57
  • 1
    @3isenHeim This \roundup command is fully expandable, so you can use it anywhere
    – egreg
    Commented Sep 15, 2021 at 8:04

You must log in to answer this question.

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