user1721135
user1721135

Reputation: 7092

php round suitable for cart total?

I am using this

$grandtotal = round ($grandtotal, 2);

to echo my calculated grandtotal from a shopping cart, as without it i would get something like this:

27.999999997 due to decimals in the prices.

Question,

Can i count on the floating point inaccuracy to be allways somewhere in the 0.000000 area?

If it is allways such a small number rounding shouldnt be a problem and allways return the correct total right?

Or do i need a more sophisticated approach?

The store im working on will be a food delivery and it is not expected that people would order thousands of items so that inaccuracies of 0.00000002 would accumulate to 0.1.

Upvotes: 1

Views: 641

Answers (3)

Haver
Haver

Reputation: 443

We do not use round

number_format($amount, 2, ".",""); //as you want the amount to be as much closer to real 27.99

but if you realy need to use round:

echo round(9.0, 0, PHP_ROUND_HALF_UP);   // 9
echo round(9.1, 0, PHP_ROUND_HALF_UP);   // 9
echo round(9.2, 0, PHP_ROUND_HALF_UP);   //9
echo round(9.3, 0, PHP_ROUND_HALF_UP);   // 9
echo round(9.4, 0, PHP_ROUND_HALF_UP);   // 9
echo round(9.5, 0, PHP_ROUND_HALF_UP);   // 10
echo round(9.6, 0, PHP_ROUND_HALF_UP);   // 10
echo round(9.7, 0, PHP_ROUND_HALF_UP);   // 10
echo round(9.8, 0, PHP_ROUND_HALF_UP);   // 10
echo round(9.9, 0, PHP_ROUND_HALF_UP);   // 10
echo round(27.999999997, 0, PHP_ROUND_HALF_UP); //28
echo round(27.994444, 0, PHP_ROUND_HALF_UP);   // 28

By rounding up or down you could be loosing a lot of money ex. you basket will have 10 items cost of £1.4 your lost will be £4 pence if you have 10000 items the lost will be £400.

Upvotes: 1

hakre
hakre

Reputation: 197842

It's not so much that round would not be suitable, but your data-type is not suitable. PHP's floating point numbers are not fitting for money values that you have in your question. So you are not using a suitable type for the job.

Instead use a dedicated money type. AFAIK none exists in PHP by default, you find the pattern of it described in various places, for example in the P of EAA Catalog | Money.

Upvotes: 1

cb0
cb0

Reputation: 8613

If you use the round function throughout your calculation then there should be no problem.

I've written a some accounting stuff in php and used the function with no great problems.
But be sure to check the results against some good old paper&pencil calculations. :)

Upvotes: 1

Related Questions