1

I am trying to solve this problem:

When I purchase items I receive a receipt which lists the name of all the items and their price (including tax), finishing with the total cost of the items, and the total amounts of sales taxes paid. The rounding rules for sales tax are that for a tax rate of n%, a shelf price of p contains (np/100 rounded up to the nearest 0.05) amount of sales tax.

So, ... I have a price in php:

$value = 11.25;

and I don't understand why

var_export(ceil($value * 0.05 * 10));

returns 6 and dividing per 10, the result is

var_export(ceil($value * 0.05 * 10) / 10);

0.59999999999999998


some nice experiments:

php > echo bcmul(11.25, 0.05, 3);
0.562
php > echo bcmul(ceil(11.25), 0.05, 3);
0.60
sensorario
  • 20,262
  • 30
  • 97
  • 159
  • 10
    Because floating point is not exact. Use `number_format` to round it to a particular number of decimal places. – Barmar Sep 02 '15 at 20:54
  • 1
    [What every computer scientist should know about floating-point arithmetic.](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – bishop Sep 02 '15 at 21:00

1 Answers1

2

You could read what bishop point out and also you could read this in order to understand what is the problem.

Now talking about a solution, you could use PHP BCMath extension which should be used when you want to work with precision mathematical numbers

For arbitrary precision mathematics PHP offers the Binary Calculator which supports numbers of any size and precision, represented as strings.

One solution (a ugly one) could be this

$value = 11.25;

var_export(bcdiv(ceil($value * 0.05 * 10), 10, 1)); // Output '0.6'

Here I am using the bcdiv from the mentioned extension.

Community
  • 1
  • 1
Richard Pérez
  • 1,467
  • 3
  • 15
  • 18