开发者

bcadd really necessary when calculating shopping cart total?

开发者 https://www.devze.com 2023-02-27 08:34 出处:网络
Given the fact that a floating point 开发者_高级运维is imprecise and that I should use the the BCMath function to get precise results, is it really necessary to use price strings in PHP and add them u

Given the fact that a floating point 开发者_高级运维is imprecise and that I should use the the BCMath function to get precise results, is it really necessary to use price strings in PHP and add them up with bcadd when making a 'simple' shopping cart?

Given the following example, why shouldn't I use a rounded float?

I'm looking for a best practice for calculating the order total for a shopping cart.

    $floatTotal = 0.00;
$stringTotal = '0.00';

for($i=0; $i<1000; $i++) {
    $floatTotal += 0.1; 
}
echo "float value: ";
printf('%.40f', $floatTotal); //99.9999999999985931253831950016319751739502

echo "<br>\n";

echo "rounded float value: ". round($floatTotal); //100

echo "<br>\n";

for($i=0; $i<1000; $i++) {
    $stringTotal = bcadd($stringTotal, '0.1', 2);
}

echo 'string value: '.$stringTotal.'<br>'; //100.00


You should never use floating point values for currencies. They are not accurate. Instead, store monetary values in the smallest units (cents, pennies, etc.) so you can use integers. In that case there's no reason to use the bcmath library unless you are dealing with huge values which is rather unlikely.


Despite this being asked a while ago and aside from storing the values using the smallest denominator.

PHP has a way of messing things up in the long run without using BCMath, but it depends on the precision you set in PHP, regardless of the float value size. IIRC MySQL will output your decimal values as strings to PHP not floats. Performing any math on the string values from within PHP will convert them to a float. The BC math functions also do not round the values, they are truncated to the defined precision.

That said, since you are storing your values as decimal in MySQL you can perform your math from the database instead of utilizing the very costly PHP bcmath functions.

Reference: https://dev.mysql.com/doc/refman/5.0/en/precision-math.html

Possibly even create views, triggers, or stored procedures for processing the values to save you time and for consistency or for working with an ORM.

SELECT ((quantity * price) * tax) AS total FROM Table1;  

http://sqlfiddle.com/#!9/05435/1

*Note I set size and scale as 32,16 for the decimal and float columns to display binary precision. I also used the common 0.2*0.3 example.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号