Should I store a field PRICE as an int or as a float in the database?

MySQLMySQLi Database

You do not need to store a field PRICE as an int or as float in the database. For this, you can set the DECIMAL()..

Most of the time integers can be used to represent the float point numbers and these integers are internally cast into DECIMAL() data type. Therefore, if you have field PRICE then always use DECIMAL() data type. The syntax is as follows −

DECIMAL(M,D);

Here, M represents the ‘TotalNumberOfDigit’ and D represents the ‘Number OfDigitAfterDecimalPoint’.

To understand the above concept, let us create a table with field PRICE as DECIMAL data type. The query is as follows −

mysql> create table Decimal_Demo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> PRICE DECIMAL(18,2),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (1.63 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into Decimal_Demo(PRICE) values(99999999999999.99);
Query OK, 1 row affected (0.11 sec)
mysql> insert into Decimal_Demo(PRICE) values(10000000000000.99);
Query OK, 1 row affected (0.36 sec)

Now you can display all records from the table using a select statement. The query is as follows −

mysql> select *from Decimal_Demo;

The following is the output −

+----+-------------------+
| Id | PRICE             |
+----+-------------------+
|  1 | 99999999999999.99 |
|  2 | 10000000000000.99 |
+----+-------------------+
2 rows in set (0.00 sec)
raja
Published on 26-Feb-2019 15:56:10
Advertisements