Alin Alin - 1 month ago 17
Node.js Question

node.js numeric with decimal and roundings in knex

In my postgres table I have a field which is type

numeric (30,16)
where I store numbers with many decimals. I need to compute these numbers.

I am using
knex
and by default it returns these values as
String
so in order to have as number, I've tried:

var types = require('pg').types
types.setTypeParser(1700, 'text', parseFloat);


However this still doesn't work right, for instance from
488.1456218300001000
and I substract
300
I can obtain something like
188.1456218300001500
.

What do I need to do in node.js to properly handle operations without any rounding errors?

Answer Source

The problem you are encountering has nothing to do with knex or Postgres, it's just the way JavaScript's numbers work – their precision is not high enough to handle that many decimal digits.

You can find more info on this in this related SO question.

As suggested in the comments, if you really need higher precision, you can use a library like big.js.

You can see how it works in this fiddle, look at this code example:

const Big = require('big.js');    

const a = 400.12345678901234567890;
console.log(a - 300); // 100.12345678901232 :-(

const b = new Big('400.12345678901234567890');
console.log(b.minus(300).toString()); // 100.1234567890123456789 :-)