In MySQL, what is the preferred column type for storing a product's price (or currencies in general)? Google learned me DECIMAL of FLOAT is often used, but I wonder which one is better.
I'm storing prices ranging from 0.01 to 25.00. Of course higher values could also be possible. (Note: I'm not asking for copy-pasta code, I'm just giving you more information which could help you form a more complete answer).
Thanks
We can store the money values in MySQL in decimal(value1,value2). Here, value1 is the total range including value2. The value2 specifies the number of digits after the decimal point.
Numeric Data Types The p parameter indicates the maximum total number of digits that can be stored (both to the left and to the right of the decimal point). p must be a value from 1 to 38. Default is 18.
The best datatype to use for currency in C# is decimal. The decimal type is a 128-bit data type suitable for financial and monetary calculations. The decimal type can represent values ranging from 1.0 * 10^-28 to approximately 7.9 * 10^28 with 28-29 significant digits.
Numeric data types are normally used to store data like price, salary etc.
Decimal is the one I would use
The basic difference between Decimal/Numeric and Float : Float is Approximate-number data type, which means that not all values in the data type range can be represented exactly. Decimal/Numeric is Fixed-Precision data type, which means that all the values in the data type reane can be represented exactly with precision and scale.
Converting from Decimal or Numeric to float can cause some loss of precision. For the Decimal or Numeric data types, SQL Server considers each specific combination of precision and scale as a different data type. DECIMAL(4,2) and DECIMAL(6,4) are different data types. This means that 11.22 and 11.2222 are different types though this is not the case for float. For FLOAT(6) 11.22 and 11.2222 are same data types.
Field type "Decimal" is good.
If you have highe prices then you can use product_price decimal(6,2) NOT NULL,
i.e. you can store prices up to 6 digits with decimal point before 2 digits.
Maximum value for field product_price decimal(6,2) NOT NULL,
will store price up to 9999.99
If all prices are between 0.01 to 25.00 then product_price decimal(4,2) NOT NULL,
will be good, but if you will have higher prices then you can set any values in decimal(4,2)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With