Postgresql从float8到decimal(24,8)的错误转换
使用Postgres 12.4我发现float8到decimal(24,8)之间的舍入有些不一致
通过执行
select
29314.630053404966::float8::decimal(24,8) as num1,
29314.630053404966::decimal(24,8) as num2
返回是:
num1: 29314.63005341 -> wrong
num2: 29314.63005340 -> correct
正如你所看到的舍入不能正常工作
有什么方法可以正确地从float8转换到decimal(24,8)?
using Postgres 12.4 I found some inconsistencies rounding between float8 to decimal(24,8)
By doing
select
29314.630053404966::float8::decimal(24,8) as num1,
29314.630053404966::decimal(24,8) as num2
the return is:
num1: 29314.63005341 -> wrong
num2: 29314.63005340 -> correct
As you can see the rounding does not work properly
Any way to cast correctly from float8 to decimal(24,8)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我想存储小数点值,我总是会使用
decimal
而不是使用float8
。为什么?有一个例子
我们可以看到
0.1::float8 + 0.2::float8
将得到错误的数字。更多详细信息可以参考每个程序员都应该了解浮点运算
有一种方法可能会帮助您做到这一点,
我们可以先尝试将值转换为字符串,即在将
float8
转换为decimal(24,8)
之前。这种方式可能可行,但会导致性能问题。
sqlfiddle
I would always use
decimal
instead of usingfloat8
if I wanted to store decimal point values.why? there is an example
we can see the
0.1::float8 + 0.2::float8
will get the wrong number.more detail can refer by What Every Programmer Should Know About Floating-Point Arithmetic
There is a way that might help you do that
we can try to cast the value as a string first, Before Casting
float8
todecimal(24,8)
.This way might work, but that will cause performance issues.
sqlfiddle