1
$\begingroup$

Below is a function to round to nearest .05. The round function simply rounds up or down to the nearest first decimal place. Example 2.26 rounds to 2.3

round_to_nearst_05 = round($amount * 2, 1) / 2

The function below will round to the nearest .05. For example 2.28 will round to 2.3

My question involves calculating the change. Will the following be ALWAYS be equal (it seems to work in this case):

Let x = 3 (amount tendered)
Let y = 2.28 (sale total)

change calc 1 = X - round_to_nearst_05(Y)
change calc 2 = round_to_nearest_05(X-Y)
$\endgroup$
  • $\begingroup$ Do you mean that $\text{round}(0.73) = 0.7$ or $0.75$? $\endgroup$ – apnorton Jun 20 '13 at 13:44
  • $\begingroup$ Ah! Thanks. (I misunderstood the question.) $\endgroup$ – apnorton Jun 20 '13 at 13:47
1
$\begingroup$

Let $\text{round}$ denote your rounding function and $\text{round2}$ denote the rounding function you used to implement your function.

Assuming that $x$ is a number that isn't affected by the rounding (i.e. $\text{round}(x) = x$), I think that the two calculations will give different results only when $y$ is at a midpoint for $\text{round}$.

For instance, let $x = 3$ and $y = 2.275$. Then, calculation 1 gives you $$x - \text{round}(y) = 3 - \text{round}(2.275) = 3 - 2.3 = 0.7$$ whereas calculation 2 gives you $$\text{round}(x - y) = \text{round}(3 - 2.275) = \text{round}(0.725) = 0.75.$$

This is assuming that $\text{round2}$ rounds up at midpoints, but we would have a similar problem even if it rounds down.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.