Rounding Mode

Rounding means replacing a number with an approximate value that has a shorter, simpler, or more explicit representation. For given \(x\), if the rounded result is \(y\), there are the following rounding modes for selection.

Half to Even

Rounding: when the decimal value is 0.5, round to the nearest even number. The enumeration value is RM_HALF_TO_EVEN.

Half Away From Zero

Rounding: positive numbers are close to positive infinity, negative numbers are close to negative infinity. The enumeration value is RM_HALF_AWAY_FROM_ZERO. The formula is

\[\mathsf{y = \mathrm{sign}(x)\left\lfloor|x| + 0.5\right\rfloor = -\mathrm{sign}(x)\left\lceil-|x| - 0.5\right\rceil}\]

Towards Zero

Unconditionally round off decimals, close to zero point. The enumeration value is RM_TOWARDS_ZERO. The formula is

\[\begin{split}\mathsf{y = \mathrm{sign}(x)\left\lfloor|x|\right\rfloor = -\mathrm{sign}(x)\left\lceil-|x|\right\rceil} = {\begin{cases}\mathsf{\lfloor x\rfloor}&{\text{if}}\mathsf{\ \ x > 0,}\\ \mathsf{\lceil x\rceil}&{\text{otherwise}}.\end{cases}}\end{split}\]

Down

Rounds toward negative infinity. The enumeration value is RM_DOWN. The formula is

\[\mathsf{y = \lfloor x\rfloor = -\lceil-x\rceil}\]

Up

Rounds toward positive infinity. The enumeration value is RM_UP. The formula is

\[\mathsf{y = \lceil x\rceil = -\lfloor-x\rfloor}\]

Half Up

Rounded to the nearest positive infinity. The enumeration value is RM_HALF_UP. The formula is

\[\mathsf{y = \lceil x + 0.5\rceil = -\lfloor-x - 0.5\rfloor = \left\lceil\frac{\lfloor 2x\rfloor}{2}\right\rceil}\]

Half Down

Rounds to the nearest negative infinity. The enumeration value is RM_HALF_DOWN. The formula is

\[\mathsf{y = \lfloor x - 0.5\rfloor = -\lceil-x + 0.5\rceil = \left\lfloor\frac{\lceil 2x\rceil}{2}\right\rfloor}\]

Example

The following table lists the correspondence between x and y under different rounding modes.

\[\begin{split}\begin{array}{|c|c|c|c|c|c|c|c|} \hline ~ & \textsf{Half to} & \textsf{Half Away} & \textsf{Towards} & \textsf{Down} & \textsf{ Up } & \textsf{Half Up} & \textsf{Half Down}\\ ~ & \textsf{Even} & \textsf{From Zero} & \textsf{Zero} & ~ & ~ & ~ & ~ \\ \hline +1.8 & +2 & +2 & +1 & +1 & +2 & +2 & +2\\ \hline +1.5 & +2 & +2 & +1 & +1 & +2 & +2 & +1\\ \hline +1.2 & +1 & +1 & +1 & +1 & +2 & +1 & +1\\ \hline +0.8 & +1 & +1 & 0 & 0 & +1 & +1 & +1\\ \hline +0.5 & 0 & +1 & 0 & 0 & +1 & +1 & 0\\ \hline +0.2 & 0 & 0 & 0 & 0 & +1 & 0 & 0\\ \hline -0.2 & 0 & 0 & 0 & -1 & 0 & 0 & 0\\ \hline -0.5 & 0 & -1 & 0 & -1 & 0 & 0 & -1\\ \hline -0.8 & -1 & -1 & 0 & -1 & 0 & -1 & -1\\ \hline -1.2 & -1 & -1 & -1 & -2 & -1 & -1 & -1\\ \hline -1.5 & -2 & -2 & -1 & -2 & -1 & -1 & -2\\ \hline -1.8 & -2 & -2 & -1 & -2 & -1 & -2 & -2\\ \hline \end{array}\end{split}\]