MySQL JSON column loses decimal precision when a JSON object is inserted as a string literal

I am trying to insert a JSON document into a MySQL JSON column and notice that decimal precision is lost.

{"value": 212765.700000000010000}

Returns to

{"value": 212765.7}

I tried pasting directly through the MySQL Workbench, and I noticed different behavior depending on how I do it. For instance:

insert into json_test values ('{"value": 212765.700000000010000}');

It produces the same result .. however, the following works:

insert into json_test values (json_object('value', 212765.700000000010000));

insert, JSON json_ *, .. JDBC, SQL ( JSON , ) , , , .

?

+4
1

, , -, , MySQL JSON, , DOUBLE . JSON , , JSON, UPDATE :

mysql> SELECT VERSION();
+-------------------------+
| VERSION()               |
+-------------------------+
| 5.7.20-0ubuntu0.16.04.1 |
+-------------------------+
1 row in set (0.01 sec)

mysql> CREATE TABLE json_test (id INT PRIMARY KEY, jv JSON);
Query OK, 0 rows affected (0.20 sec)

...

mysql> INSERT INTO json_test (id, jv) VALUES (1, '{"value": "212765.700000000010000"}');
Query OK, 1 row affected (0.11 sec)

mysql> INSERT INTO json_test (id, jv) VALUES (2, '{"whatever": "foo"}');
Query OK, 1 row affected (0.06 sec)

mysql> INSERT INTO json_test (id, jv) VALUES (3, '{"value": "212765.700000000010000", "whatever": "bar"}');
Query OK, 1 row affected (0.01 sec)

mysql> SELECT * FROM json_test;
+----+--------------------------------------------------------+
| id | jv                                                     |
+----+--------------------------------------------------------+
|  1 | {"value": "212765.700000000010000"}                    |
|  2 | {"whatever": "foo"}                                    |
|  3 | {"value": "212765.700000000010000", "whatever": "bar"} |
+----+--------------------------------------------------------+
3 rows in set (0.01 sec)

... UPDATE CAST DECIMAL:

mysql> UPDATE json_test SET jv = JSON_REPLACE(jv, '$.value', CAST(JSON_EXTRACT(jv, '$.value') AS DECIMAL(21,15))) WHERE JSON_TYPE(JSON_EXTRACT(jv, '$.value')) = 'STRING';
Query OK, 2 rows affected (0.04 sec)
Rows matched: 2  Changed: 2  Warnings: 0

mysql> SELECT * FROM json_test;
+----+------------------------------------------------------+
| id | jv                                                   |
+----+------------------------------------------------------+
|  1 | {"value": 212765.700000000010000}                    |
|  2 | {"whatever": "foo"}                                  |
|  3 | {"value": 212765.700000000010000, "whatever": "bar"} |
+----+------------------------------------------------------+
3 rows in set (0.01 sec)

mysql> SELECT JSON_TYPE(JSON_EXTRACT(jv, '$.value')) AS jt FROM json_test WHERE id=1;
+---------+
| jt      |
+---------+
| DECIMAL |
+---------+
1 row in set (0.01 sec)
0

Source: https://habr.com/ru/post/1690095/


All Articles