C libpq: get float value from numeric

半腔热情 提交于 2019-12-11 03:43:02

问题


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

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.


回答1:


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 floating point. They cannot represent all decimal numbers without rounding errors, and they can't represent unlimited precision numbers because they have fixed precision.

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.

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.

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.

Libraries include:

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

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

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.



来源:https://stackoverflow.com/questions/32651069/c-libpq-get-float-value-from-numeric

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!