PostgreSQL-舍入浮点数 [英] PostgreSQL - rounding floating point numbers
问题描述
我在PostgreSQL 9.2中有一个关于浮点数的新手问题。
I have a newbie question about floating point numbers in PostgreSQL 9.2.
是否有一个函数可以直接舍入浮点数,即无需转换数字到数字类型?
Is there a function to round a floating point number directly, i.e. without having to convert the number to a numeric type first?
此外,我想知道是否存在以任意度量单位四舍五入的函数,例如最接近的0.05?
Also, I would like to know whether there is a function to round by an arbitrary unit of measure, such as to nearest 0.05?
首先将数字转换为小数形式时,以下查询可以正常工作:
When casting the number into a decimal form first, the following query works perfectly:
SELECT round(1/3.::numeric,4);
round
--------
0.3333
(1 row)
Time: 0.917 ms
但是,我真正想要实现的是以下内容:
However, what really I'd like to achieve is something like the following:
SELECT round(1/3.::float,4);
当前会给我以下错误:
ERROR: function round(double precision, integer) does not exist at character 8
Time: 0.949 ms
谢谢
推荐答案
您可以按照以下方式完成此操作
You can accomplish this by doing something along the lines of
select round( (21.04 /0.05 ),0)*0.05
其中 21.04
是要舍入的数字, 0.05
是准确性。
where 21.04
is the number to round and 0.05
is the accuracy.
这篇关于PostgreSQL-舍入浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!