I have a database table with some fields, one of them, cost, is set to the DECIMAL data type. I set the parameters to 4,2, which should allow 4 numbers before the decimal point, and 2 afterwards.
(I’ve been told that the 4 here is the total amount, and the 2 is the amount after the decimal, could somebody please clear that up on a side note?)
When I insert data via a POST request (the value 3.80 for example) the data stored to my database is actually 99.99.
What am I doing wrong to cause this?
Here’s the table:
CREATE TABLE IF NOT EXISTS `mytable` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(256) NOT NULL,
`cost` decimal(4,2) NOT NULL,
PRIMARY KEY (`id`)
)
Here’s my add query:
INSERT INTO mytable (`id`,`title`,`cost`)
VALUES (0, 'test title', '3.80')
Update:
It works after I changed 4,2 to 6,2
MySql decimal types are a little bit more complicated than just left-of and right-of the decimal point.
The first argument is precision, which is the number of total digits. The second argument is scale which is the maximum number of digits to the right of the decimal point.
Thus,
(4,2)can be anything from-99.99to99.99.As for why you’re getting
99.99instead of the desired3.80, the value you’re inserting must be interpreted as larger than99.99, so the max value is used. Maybe you could post the code that you are using to insert or update the table.Edit
Corrected a misunderstanding of the usage of scale and precision, per http://dev.mysql.com/doc/refman/5.0/en/numeric-types.html.