0

I need to store in a column values like 0.0000003215218845

What type does my column needs to be? I've tried making it real or float but when I run a select query, to value I get is 3.21522e-07

What type does my column needs to be in order for the select query to return fully 0.0000003215218845 value?

3
  • 1
    numeric ordecimal (synonyms) - Postgres numeric types Commented Aug 1, 2017 at 12:45
  • you can store them in float ok. 3.215218845e-07 is equal to 0.0000003215218845 Commented Aug 1, 2017 at 12:52
  • 2
    Float lacks real precision. If you need an exact answer it should be avoided. Numeric has a limit that's in the thousands of characters and still be accurate, but it's slower. Commented Aug 1, 2017 at 20:55

2 Answers 2

2

If you want to control how a floating point number is converted to a string, use the to_char function:

SELECT 0.0000003215218845::double precision;

     float8
-----------------
 3.215218845e-07
(1 row)

SELECT to_char(0.0000003215218845::double precision,
               'FM90.9999999999999999');

     to_char
------------------
 0.00000032152188
(1 row)

The difference in value is the rounding error.

Use numeric for values with arbitrary precision.

Sign up to request clarification or add additional context in comments.

3 Comments

Finally something that works. From what I've read in order to perform calculations exactly I would need either numeric or decimal. But how should I specify the precision and scale to fit all the values up to 20 decimals for instance. I need to do the calculations exactly so a type which isn't stored exactly won't work
Use a type like numeric(21,20) (that would be for one position before the decimal separator and 20 after).
Note that you do not HAVE to declare the precision.
2

See postgres documentation: numeric-types v.9 or numeric v.11. could help. But you must be aware:

  • The tool, you do your queries with, often does not return the data in full resolution. The numbers might be stored correctly, you must probably change the format, how you output it.
  • float and double are stored as binary so the data might be rounded before being stored. So perhaps if you want to store decimal data in their exact form, the fixed-point types might be more suitable for your application.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.