0

pg-promise returns the decimal values as string. How do I fix this?

select round(avg(numcol),2)::decimal from details
Giri
  • 451
  • 1
  • 4
  • 13
  • The same as [here](https://stackoverflow.com/questions/42901913/decimal-value-in-postgresql-returned-as-string-in-node-js), and solution is similar to [this](https://stackoverflow.com/questions/39168501/pg-promise-returns-integers-as-strings). – vitaly-t Oct 06 '20 at 09:10
  • @vitaly-t Thanks for sharing the solution. But the thing is I am new to pg-promise. A complete example would be helpful. – Giri Oct 06 '20 at 10:16
  • Isn't it what I gave you in my answer? What else are you expecting? – vitaly-t Oct 06 '20 at 11:49
  • I am not sure where to use the code you provided in the answer. So I just used javascript parseFloat in db.each(query, values, data=>{...}). It worked. – Giri Oct 06 '20 at 11:53
  • You should learn the basics of using the library first, it is all very clear there. This wouldn't be the right place for discussing how to use the library. – vitaly-t Oct 06 '20 at 12:51

1 Answers1

-1

Following the links I provided in the comments (one and two), you should see that JavaScript simply doesn't have the required precision, so automatic conversion may result in lost precision.

If you do not care about that, you can apply JavaScript standard parseFloat:

const types = pgp.pg.types; // types conversion interface

// for real/float4:
types.setTypeParser(700, parseFloat);

// for double precision/float8:
types.setTypeParser(701, parseFloat);

// for arrays of float4:
const parseFloat4Array = types.getTypeParser(1021);
types.setTypeParser(1021, a => parseFloat4Array(a).map(parseFloat));

// for arrays of float8:
const parseFloat8Array = types.getTypeParser(1022);
types.setTypeParser(1022, a => parseFloat8Array(a).map(parseFloat));

Otherwise, use a specialized library for dealing with decimals.

vitaly-t
  • 24,279
  • 15
  • 116
  • 138