C libpq:从数字获取浮点值 [英] C libpq: get float value from numeric

查看:169
本文介绍了C libpq:从数字获取浮点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,其中浮点值使用数字类型表示。如何使用libpq lib从此字段中获取浮点值?

I have a table with float value represented using numeric type. How can I get float value from this field using libpq lib?

postgres中有一种特殊的浮点类型格式,但是我必须使用具有数字字段的现有数据库。我没有在Postgres文档中找到有关此信息的信息,因此感谢所有信息。

There is a specialized format for float type in postgres, but I have to work with existing database with numeric fields. I haven't found information about it in the Postgres documentation so every info is appreciated.

推荐答案

严格地说,您可以 t 获取数字的精确浮点表示。无论如何,不​​是任何任意数字

Strictly you can't get an accurate float representation of a numeric. Not for any arbitrary numeric anyway.

数字是内部表示为二进制编码的十进制字符串的任意精度十进制浮点数。通常以十进制数字的文本字符串形式发送到客户端或从客户端发送。

numeric is arbitrary-precision decimal floating point represented internally as binary-coded decimal strings. It's usually sent to and from the client as a text string of decimal digits.

float / double are fixed-precision binary 浮点数。它们不能表示没有舍入错误的所有十进制数字,并且它们不能表示无限精度的数字,因为它们具有固定的精度。

float/double are fixed-precision binary floating point. They cannot represent all decimal numbers without rounding errors, and they can't represent unlimited precision numbers because they have fixed precision.

您的数字数字(18,15),即精度18,小数位数15。 double precision 有15-17个有效数字,具体取决于确切值。因此,由于四舍五入,您可能会丢失数据。

Your numerics are numeric(18,15), i.e. precision 18, scale 15. double precision has 15-17 significant digits, depending on the exact value. So you may lose data due to rounding.

如果您不介意,则可以使用通常的方法从文本中解析浮点值,例如 sscanf ,在 PQgetvalue 的文本输出上。

If you don't mind that, you can use the usual methods for parsing a floating point value from text, like sscanf, on the textual output of PQgetvalue.

需要保留准确的十进制浮点数:避免舍入损失并在往返之间保留准确的值,您将需要使用十进制浮点库。对于任何数字,您需要任意精度的十进制支持。对于数字(18,15),您可以几乎使其适合IEEE-754:2008 64位十进制,但是您确实需要128-

If you need to retain accurate decimal floating point: avoid rounding losses and preserve exact values across round trips, you're going to need to use a decimal floating point library. For any numeric you'd need arbitrary-precision decimal support. For numeric(18,15) you can almost fit it in a IEEE-754:2008 64-bit decimal, but you really need 128-bit decimal to be safe.

库包括:

  • Intel's Decimal Floating Point library
  • IBM's decimal floating point library
  • GNU MFPR - arbitrary precision
  • decNumber
  • libmpdec - arbitrary precision

较新的gcc也包括对IEEE-754:2008浮点的支持。

Newer gcc includes support for IEEE-754:2008 floating point too.

Python具有任意精度 decimal.Decimal 类型(导入十进制)的小数。 psycopg2 应该可以使用它。因此,您可以考虑将其作为替代方案。

Python has arbitrary-precision decimal with the decimal.Decimal type (import decimal). psycopg2 should be able to use this. So you might consider this as an alternative.

这篇关于C libpq:从数字获取浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆