Link to home
Start Free TrialLog in
Avatar of hrolsons
hrolsonsFlag for United States of America

asked on

Strange value showing up in Array

$productByCode = $db_handle->runQuery("SELECT * FROM tblproduct WHERE code='LPN45'");

$itemArray = array(
   $productByCode[0]["code"] => array(
   'id' => $productByCode[0]["id"],
   'name' => $productByCode[0]["name"],
   'code' => $productByCode[0]["code"],
   'quantity' =>2,
   'price' => $productByCode[0]["price"],
   'image' => $productByCode[0]["image"]
   )
);               
echo print_r($productByCode[0]["price"]);

Open in new window

Outputs:
800.001

Open in new window

But the value of price in tblproduct is 800.00 without the extra 1.
Any clue what could be happening?
Avatar of David Johnson, CD
David Johnson, CD
Flag of Canada image

format as decimal with 2 digits to the right.
These things happen maybe because of currency rate calculations or VAT or Tax.

echo round($productByCode[0]["price"], 2);
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
isn't echo print_r redundant?

What is the number supposed to show up as?
Avatar of hrolsons

ASKER

Yes, I'm able to format it to (2) decimal places and it displays properly.  But I'm wondering why it's showing up in the first place and whether it's indicative of a bigger problem that I'm having, which I'll post in a new question if this thread doesn't resolve the issue.

It is a double(10,2)
Arnold seems to be onto something.

For those of you curious:
echo print_r($productByCode[0]["price"]);
echo "<br>";
echo round($productByCode[0]["price"], 2);
echo "<br>";
echo $productByCode[0]["price"];
echo "<br>";
print_r($productByCode[0]["price"]);

Open in new window

Produces:
800.001
800
800.00
800.00

Open in new window


(No points, someone else already suggested DECIMAL ...)
It is a double(10,2)                                   
Double is an approximate type, which isn't suitable for expressing things with a precise value like currency.
https://dev.mysql.com/doc/refman/8.0/en/floating-point-types.html

Note "...As of MySQL 8.0.17, the nonstandard FLOAT(M,D) and DOUBLE(M,D) syntax is deprecated and you should expect support for it to be removed in a future version of MySQL."       

For currency, use a fixed type like DECIMAL
https://dev.mysql.com/doc/refman/5.7/en/fixed-point-types.html