更新 MySQL table 时字符串字段丢失小数精度
losing decimal precision in string filed when updating MySQL table
我有一个 varchar(255)
数据类型的文件。当我 运行 这个查询时:
update sample_tbl
set in_order_real = in_order_real + 21.215541764099030466
where id = 15
它会删除多余的小数。
例如 in_order_real
数字是 0
并且当我 运行 这个查询时它只保留一些小数并四舍五入,而它是一个字符串字段。我该如何解决这个问题?
您必须将字符串值转换为具有适当精度的 DECIMAL。
CREATE TABLE sample_tbl (id INT, in_order_real VARCHAR(255))
SELECT 15 id, 1.23 in_order_real
UNION ALL
SELECT 16, 1.23;
SELECT * FROM sample_tbl;
id
in_order_real
15
1.23
16
1.23
update sample_tbl
set in_order_real = in_order_real + 21.215541764099030466
where id = 15;
update sample_tbl
set in_order_real = CAST(in_order_real AS DECIMAL(30, 18)) + 21.215541764099030466
where id = 16;
SELECT * FROM sample_tbl;
id
in_order_real
15
22.44554176409903
16
22.445541764099030466
db<>fiddle here
如果您不知道实际的小数位数,请使用最大可能值。此外,您可以 trim 结果中的尾随零。
FLOAT
保留 24 个有效位——大约 7 个有效的十进制数字。
DOUBLE
: 53 和 16
因此,将 21.215541764099030466 放入 FLOAT
后大约 7 位数字会出现乱码:~21.21554。对于 DOUBLE
:~21.21554176409903
无法在 VARCHARs
中进行算术运算;它被转换为 DOUBLE
或 DECIMAL
.
你的号码是从哪里来的?为了钱,用DECIMAL(..., 2)
;对于传感器读数,请使用 FLOAT
.
我有一个 varchar(255)
数据类型的文件。当我 运行 这个查询时:
update sample_tbl
set in_order_real = in_order_real + 21.215541764099030466
where id = 15
它会删除多余的小数。
例如 in_order_real
数字是 0
并且当我 运行 这个查询时它只保留一些小数并四舍五入,而它是一个字符串字段。我该如何解决这个问题?
您必须将字符串值转换为具有适当精度的 DECIMAL。
CREATE TABLE sample_tbl (id INT, in_order_real VARCHAR(255)) SELECT 15 id, 1.23 in_order_real UNION ALL SELECT 16, 1.23; SELECT * FROM sample_tbl;
id in_order_real 15 1.23 16 1.23
update sample_tbl set in_order_real = in_order_real + 21.215541764099030466 where id = 15; update sample_tbl set in_order_real = CAST(in_order_real AS DECIMAL(30, 18)) + 21.215541764099030466 where id = 16;
SELECT * FROM sample_tbl;
id in_order_real 15 22.44554176409903 16 22.445541764099030466
db<>fiddle here
如果您不知道实际的小数位数,请使用最大可能值。此外,您可以 trim 结果中的尾随零。
FLOAT
保留 24 个有效位——大约 7 个有效的十进制数字。
DOUBLE
: 53 和 16
因此,将 21.215541764099030466 放入 FLOAT
后大约 7 位数字会出现乱码:~21.21554。对于 DOUBLE
:~21.21554176409903
无法在 VARCHARs
中进行算术运算;它被转换为 DOUBLE
或 DECIMAL
.
你的号码是从哪里来的?为了钱,用DECIMAL(..., 2)
;对于传感器读数,请使用 FLOAT
.