如何 select 按尾数长度浮动值?

How to select float values by mantissa length?

我有一列具有双精度值。我试图 select 仅那些精度大于十分之一的(例如,24.13、1.347 等)。

我知道我可以将浮点数转换为字符串并使用以下方法根据字符串长度进行查询:

select * from schema.table where char_length(to_char(float_column, 'FM999999999D999999999')) > 3;

这将 return 所有小数点后一位以上的行 如果 数字的整数部分是个位数(例如,它将 return 24.1).

如何 select 任意长度大于 1 的浮点值?

如果您将值存储为 numeric(定点与浮点),那么您可以简单地执行:

where floor(col * 100) <> floor(col * 10) * 10

不幸的是,在某些边缘情况下,此逻辑不适用于浮点数,因为您可以获得类似 21.99999999997 的结果。

使用split_part():

with my_table(float_column) as (
values
(24.13::float), (1.347), (12345), (.1)
)

select float_column, split_part(float_column::text, '.', 2)
from my_table;

 float_column | split_part 
--------------+------------
        24.13 | 13
        1.347 | 347
        12345 | 
          0.1 | 1
(4 rows)

因此您的查询可能如下所示:

select *
from my_table 
where length(split_part(float_column::text, '.', 2)) > 1;

 float_column 
--------------
        24.13
        1.347
(2 rows)    

查找舍入错误:

where round(float_column,1) <> round(float_column,5)