Decimal value in Postgresql returned as String in Node.js

回眸只為那壹抹淺笑 提交于 2021-02-07 19:09:22

问题


When I run a query to my postgresql database on a node.js server, the value that I am getting is of variable type string when in fact it is a decimal in the postgresql database.

I am not sure why my decimals or even bigInts are returning as type strings. I am using knex as my ORM if that makes a difference. So far what I have read online is not very clear about what to do, and it seems as if this happens automatically to preserve precision???

What is the best work-around for this? Is it best to convert the string variable I am returned from my query into a decimal using parseFloat?


回答1:


Both decimal and bigint types may contain values that are too large to "fit" in JavaScript's Number:

  • Number.MAX_SAFE_INTEGER (JS): 9007199254740991
  • bigint: -9223372036854775808 to 9223372036854775807
  • decimal: up to 131072 digits before the decimal point; up to 16383 digits after the decimal point

If you're quite certain that the values in your database will fit in Number, you can convert them (I don't know Knex, but perhaps it has some sort of hook system that you can use to transform data that was retrieved from the database), or change your database schema to contain "smaller" row types.

Alternatively, there are also various "big integer" packages for Node that you might be able to use.



来源:https://stackoverflow.com/questions/42901913/decimal-value-in-postgresql-returned-as-string-in-node-js

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