Sunday, January 16, 2022

[FIXED] Incorrect record in DB of decimal field of the form

Issue

I want to write in the database values ​​from 'last_price' = 9.12345678 (I need 8 characters after the dot)

CakePHP - last 3.6.7, PHP 7.2x64, MySQL 5.7x64, Field 'last_price' type in the database: DECIMAL 20, 8

Controller:

 public function add ()
    {
        // debug ($ this-> request-> getData ());
        $ pair = $ this-> Pairs-> newEntity ();
        if ($ this-> request-> is ('post')) {
            $ pair = $ this-> Pairs-> patchEntity ($ pair, $ this-> request-> getData ());
            // debug ($ pair);
            if ($ this-> Pairs-> save ($ pair)) {
                $ this-> Flash-> success (__ ('The pair has been saved.'));
                return $ this-> redirect (['action' => 'index']);
            }
            $ this-> Flash-> error (__ ('The pair could not be saved. Please, try again.'));
        }
        $ exchanges = $ this-> Pairs-> Exchanges-> find ('list', ['limit' => 200]);
        $ this-> set (compact ('pair', 'exchanges'));
    }

Content $ this-> request-> getData ():

[
'exchange_id' => '1',
'title' => '12121',
'last_price' => '9.12345678',
'favorites' => '0'
]

PairsTable.php (model)

 

$ validator
            -> decimal ('last_price', 8)
            // -> maxLength ('last_price', 30)
            -> requirePresence ('last_price', 'create')
            -> notEmpty ('last_price');

I'm click to ADD, but the following query is coming to the database:

2018-07-24 07:09:19 Debug: duration = 0 rows = 1 INSERT INTO pairs (exchange_id, title, last_price, favorites, created, modified) VALUES (1, '5453534534543', '9.123457', 0, '2018 -07-24 07:09:19 ',' 2018-07-24 07:09:19 ')

WHY 'last_price' = 9.123457 ?!!!???? I see- it is written in the database as 9.12345700

Why not 9.12345678 ??


Solution

To help you solve this, I set up a table with decimal_value (decimal(18,12)), float_value (float(18,12)), double_value (double(18,12)).

Image of retrieved data from database

double_value was accurate on all three inserts.

Change column type to DOUBLE. Clear the orm_cache.



Answered By - Christian

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.