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
The Basic syntax of Decimal data type in SQL Server Where, p stands for Precision, the total number of digits in the value, i.e. on both sides of the decimal point. s stands for Scale, number of digits after the decimal point.
SELECT ROUND(-4.535,2); Explanation: The above MySQL statement will round the given number -4.535 up to 2 decimal places.
For Example − DECIMAL(4,2), it means you can take 4 digits total and 2 digit after decimal point. The second parameter is up to 2 digit after decimal point. Case 1 − 12.34 is valid. Case 2 − 123.4 is not valid.
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.99
to 99.99
.
As for why you're getting 99.99
instead of the desired 3.80
, the value you're inserting must be interpreted as larger than 99.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.
Yes, 4,2 means "4 digits total, 2 of which are after the decimal place". That translates to a number in the format of 00.00
. Beyond that, you'll have to show us your SQL query. PHP won't translate 3.80 into 99.99 without good reason. Perhaps you've misaligned your fields/values in the query and are trying to insert a larger number that belongs in another field.
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