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?
views:
113answers:
7The question I always ask myself when considering string or numeric (int, double, etc.) datatypes is, "Am I going to do math with them?" If the answer is yes, which I must assume it is in your case, I go with the numeric value. If the answer is no, I choose the string value.
With the information you give, it seems better to just use an integer, so you can sort and query with numerical values instead of string values. An int would be better than a floating point as it wont have weird half cent problems.
ie, you don't want 6.77 to be greater than 12.54, nor do you want something with the price 6.4312313141.
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).
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.
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.
I personally prefer integers to store it as cent value, 650 instead of 6.50. Easy sorting, no rounding problems and easy to display in whatever format to your users.
You might want to check out the Time and Money project on sourceforge. Full disclosure: I haven't actually looked through the project much, but it seems like it would give you some good ideas about handling such things.