# Rounding up to decimal pgfmath

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}

\end{document}


However, sometimes it poses problem.

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

How can I right this behavior ?

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.

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

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