0

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
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

2 Answers2

1

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);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    @AlexanderMills That's rounding values and coercing them to plain `number`s, which I thought you'd want to avoid when using a bignumber library. – Bergi Nov 27 '22 at 20:42
0

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.

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817