postgresql - varchar postgresql 的 double

标签 postgresql casting precision

我必须将一个数据类型为 double 字段的表修改为 varchar,更改已成功执行,但是数据发生了变化,我不明白 postgres 在双向转换时做了什么。

Postgres 版本:PostgreSQL 10.4,由 Visual C++ build 1800 编译,64 位

ALTER TABLE my_table ALTER COLUMN field_double_precision TYPE varchar;

--After the change this is my problem, new value is very different to old value

id     |old_value  |new_value              |
-------|-----------|-----------------------|
9009   |0.06       | 0.059999999999999998  |
9010   |0.56       | 0.56000000000000005   |
9011   |0.068      | 0.068000000000000005  |
9012   |0.568      | 0.56799999999999995   |

我知道数值会因近似值而变化,但我必须不惜一切代价避免这种情况。

我的测试:

SELECT  CAST (0.059999999999999998 AS DOUBLE PRECISION) old_value;

old_value |
----------|
0.06      |

-----------------------------------------------------------------------
SELECT  CAST (0.059999999999999998 AS double PRECISION)::VARCHAR new_value;

new_value            |
---------------------|
0.059999999999999998 |

我可以保持新旧值相等吗?当 postgres 将 double 格式化为 varchar 时会发生什么?

最佳答案

在运行 ALTER TABLE 之前将数据类型更改为 character varying 的语句, 请确保您运行以下语句:

SET <a href="https://www.postgresql.org/docs/current/runtime-config-client.html#GUC-EXTRA-FLOAT-DIGITS" rel="noreferrer noopener nofollow">extra_float_digits</a> = 0;

这将导致 PostgreSQL 在将 float 呈现为字符串时抑制无关紧要的小数位。

关于postgresql - varchar postgresql 的 double ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55699384/

相关文章:

C# dll 中的 C# 转换异常

c++ - 为什么左值转换有效?

c - 使用顺序 bbp 计算 pi 时丢失精度(使用 GMP)

math - float 学有问题吗?

sql - 如何在 postgresql 中获取唯一约束的名称?

c# - Linq 强制转换 Xelement 错误 : Unable to cast object of type 'System.Xml.Linq.XElement' to type 'System.IConvertible'

python - 在列值中查找子字符串

ios - Metal 着色语言中的浮点精度问题

postgresql - 使用 cloudconnect 加载 PostgreSQL 数据库

postgresql - 我如何指示 postgresql plpython 函数参数可以是任何类型?