Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing price in PHP. What is better double or string?

I've been making "Product Object" for my app and I've been setting attributes, when suddenly I got to price attribute and stumbled upon it with question what type better to choose? I understand, that for PHP it doesn't matter so much, but lets say for MySQL it does.
Any suggestions?

like image 993
Eugene Avatar asked Aug 10 '10 22:08

Eugene


3 Answers

Neither is appropriate.

Prices should be stored as DECIMAL or INT, because they have a fixed number of decimal points. Using floats is not a good idea as values will get rounded. Strings are problematic because you won't be able to do comparisons.

like image 113
quantumSoup Avatar answered Oct 09 '22 21:10

quantumSoup


Real number types are better for numbers because you can do proper comparisons with them (e.g., price < 10.0). However, they do introduce problems with precision (things like 3.0 = 2.9999999999). It's best to use a native Decimal type in this case, but lacking that, I would store the prices as an integer number of cents (e.g., 6.77 => 677), then divide by 100 before presenting the number to the user. That way you get the number operations in the database, and you get the precision (assuming that precision of 1 cent is enough).

like image 23
Gintautas Miliauskas Avatar answered Oct 09 '22 21:10

Gintautas Miliauskas


There's a detailed explanation of the "best practices" solutions for this question in this SO question. Using integers is also an acceptable alternative. Regardless, it's best to use the same solution throughout your application to facilitate comparison and arithmetic.

Remember that you can always change the way the data looks before presenting it to the user, using number_format() or something else.

like image 41
cbednarski Avatar answered Oct 09 '22 20:10

cbednarski