Rounding to integer

The most basic form of rounding is to replace an arbitrary number by an integer. All the following rounding modes are concrete implementations of the abstract single-argument "round()" function presented and used in the previous sections.

There are many ways of rounding a number y to an integer q. The most common ones are

  • round down (or take the floor, or round towards minus infinity): q is the largest integer that does not exceed y.
  • round up (or take the ceiling, or round towards plus infinity): q is the smallest integer that is not less than y.
  • round towards zero (or truncate, or round away from infinity): q is the integer part of y, without its fraction digits.
  • round away from zero (or round towards infinity): if y is an integer, q is y; else q is the integer that is closest to 0 and is such that y is between 0 and q.
  • round to nearestq is the integer that is closest to y (see below for tie-breaking rules).

The first four methods are called directed rounding, as the displacements from the original number y to the rounded value q are all directed towards or away from the same limiting value (0, +∞, or −∞).

If y is positive, round-down is the same as round-towards-zero, and round-up is the same as round-away-from-zero. If y is negative, round-down is the same as round-away-from-zero, and round-up is the same as round-towards-zero. In any case, if y is integer, q is just y. The following table illustrates these rounding methods:

y round
down
(towards −∞)
round
up
(towards +∞)
round
towards
zero
round
away from
zero
round
to
nearest
+23.67 +23 +24 +23 +24 +24
+23.50 +23 +24 +23 +24 +24
+23.35 +23 +24 +23 +24 +23
+23.00 +23 +23 +23 +23 +23
0 0 0 0 0 0
−23.00 −23 −23 −23 −23 −23
−23.35 −24 −23 −23 −24 −23
−23.50 −24 −23 −23 −24 −24
−23.67 −24 −23 −23 −24 −24

Where many calculations are done in sequence, the choice of rounding method can have a very significant effect on the result. A famous instance involved a new index set up by the Vancouver Stock Exchange in 1982. It was initially set at 1000.000 (three decimal places of accuracy), and after 22 months had fallen to about 520 — whereas stock prices had generally increased in the period. The problem was caused by the index being recalculated thousands of times daily, and always being rounded down to 3 decimal places, in such a way that the rounding errors accumulated. Recalculating with better rounding gave an index value of 1098.892 at the end of the same period.[1]

你可能感兴趣的:(Rounding to integer)