PHP Classes

Do not use float for price

Recommend this page to a friend!

      Shopping Cart  >  Shopping Cart package blog  >  How to Create a Simpl...  >  All threads  >  Do not use float for price  >  (Un) Subscribe thread alerts  
Subject:Do not use float for price
Summary:Store prices as INTEGER in cents.
Messages:4
Author:Antoine Dubourg
Date:2015-09-09 07:17:05
 

  1. Do not use float for price   Reply   Report abuse  
Picture of Antoine Dubourg Antoine Dubourg - 2015-09-09 07:17:05
For storing prices, it is not advised to use float because of the possible rounding errors.

For example, storing a price like 3.5 can be stored in a float like 3.4999999.

This will be rounded to 3.5 without any problem with number formating functions.

Still, if you multiply this amount by a large value say 10000, you'll end with a total price of 34999.99 which is off by one cent...

Not a big deal but that's not what's is expected at all. Missing cents can be hard to explain to management as well...

Store prices as INTEGER in cents.

  2. Re: Do not use float for price   Reply   Report abuse  
Picture of Manuel Lemos Manuel Lemos - 2015-09-10 01:06:19 - In reply to message 1 from Antoine Dubourg
Actually the best way is to use DECIMAL data types with a fixed number of decimal places or some other CURRENCY like data type on databases that support it.

  3. Re: Do not use float for price   Reply   Report abuse  
Picture of des des - 2015-09-21 09:03:08 - In reply to message 2 from Manuel Lemos
for someone using this to learn, How would I implement DECIMAL correctly?

Regards

  4. Re: Do not use float for price   Reply   Report abuse  
Picture of Manuel Lemos Manuel Lemos - 2015-09-21 21:14:16 - In reply to message 3 from des
DECIMAL is just another type of number field. You can declare the number of decimal places you want to use for DECIMAL numbers.

dev.mysql.com/doc/refman/5.1/en/pre ...