Home > database >  properly override toJSON for mathjs bignumber
properly override toJSON for mathjs bignumber

Time:11-28

I am trying to override mathjs Bignumber using:


import * as math from 'mathjs';

export const bgn = (v: number | math.BigNumber) => {
  const z = math.bignumber(v) as math.BigNumber;
  (z as any).toJSON = () => {
    return Number(math.larger(100, z) ? math.round(z,2) : math.round(z,4)).toFixed(4);
  }
  return z;
}

but for some reason, it's still stringifying it to:

{"mathjs":"BigNumber","value":"42500"}

my goal is to stringify it to a number:

42500

CodePudding user response:

This is not currently possible with the native JSON.stringify implementation. It will become possible with the adoption of the JSON.parse source text access proposal which also includes a helper for non-lossy serialization.

You'd use it as

const text = JSON.stringify(value, (key, val) => {
  if (val instanceof math.bignumber) return JSON.rawJSON(val.toString())
  else return val;
});
console.log(text);

CodePudding user response:

OP was on the right track, this should work fine:

const math = require('mathjs');

const bgn = (v) => {
    const z = math.bignumber(v); // as math.BigNumber;
    (z).toJSON = () => {
        return Number(math.larger(z, 100) ? math.round(z, 3) : math.round(z, 5));
    }
    return z;
}

console.log(JSON.stringify(bgn(5.555555444)));

in JS instead of TS.

  • Related