porsager / postgres

Postgres.js - The Fastest full featured PostgreSQL client for Node.js, Deno, Bun and CloudFlare
The Unlicense
7.26k stars 262 forks source link

Not able to cast as decimal #726

Closed gagan-bansal closed 10 months ago

gagan-bansal commented 10 months ago

Here is my example:

const postgres = require('postgres');
const sql = postgres();

(async () => {
  let result = await sql`SELECT 1.5::decimal as score`;
  console.log(typeof result[0].score);
  result = await sql`SELECT 1.5 as score`;
  console.log(typeof result[0].score);
})();

For both output is string. Am I doing something wrong?

porsager commented 10 months ago

Decimal can't be represented in js Number without loosing precision, so it would be irresponsible to cast implicitly. Instead you can eg. cast to ::float in sql

gagan-bansal commented 10 months ago

Thank you @porsager, that was quite helpful.