openlang

grand total prints digits glued together, not a sum

Daily lines are fine (12500, 3400, 900 won), but TOTAL prints 0125003400900 KRW. Why extra zero?

const grand = rows.reduce((acc, r) => acc + r.cents, 0);
console.log(`TOTAL ${won(grand)}`);

tsc passes, Postgres 16 in docker. Same reduce as always...

The conversation continues 10

Follow the reasoning
  1. Permalink

    Is cents a bigint or numeric column? The driver hands those back as strings, and 0 + "12500" is "012500". tsc can't see that.

  2. Permalink

    yeah that's almost certainly it, 0125003400900 is just the strings concatenated, pg returns bigint and numeric as strings. either Number(r.cents) in the reduce, or cast in the query with cents::int if the values fit. if they might get big, use BigInt and format at the end.

  3. Permalink

    Nothing is wrong, your total is just very honest. Postgres sends text, JavaScript glues it. Accounting by string concatenation, and tsc says "looks fine". Of course it does.

  4. Permalink

    One caveat on cents::int: if you sum in SQL instead, the result is a string again. sum(int) returns bigint and sum(bigint) returns numeric, and the driver gives you both as text. So the Number() is needed anyway, just once at the end instead of per row.

    Summing in the query is still the better place, the database does it in one pass. The aggregate return types are in the Postgres aggregate docs.

  5. Permalink

    Funny part is the daily lines looked fine because won() formats the string "12500" the same as a number. Only the + showed it. And the extra zero in front was just my initial 0 becoming text. MDN's addition operator page says it plainly, if either side is a string, concatenate. I knew this, but never in a reduce...

Other sides of the same question

  1. rows.Next said false and the error went nowhere

    Small tool on database/sql returned half a list. No error. The code. Context with a deadline. The deadline fired in the middl…

    Replies 3Latest activity sqlgo
  2. A partial index and a parameter in the WHERE clause

    I'm writing a small job runner in Go for a class project. The setup is pgx v5 through database/sql, Postgres 16 locally, and…

    Replies 10Latest activity sqlgo
  3. SKIP LOCKED job queue and a worker that dies mid-transaction

    Job queue straight in a table. One worker in Python, one in Go. BEGIN, then SELECT id, payload FROM jobs WHERE status = 'queu…

    Replies 5Latest activity sqlgo