我试图使用以下方法覆盖mathjs Bignumber:
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;
}
但出于某种原因,它仍然把它压缩到:
{"mathjs":"BigNumber","value":"42500"}
我的目标是把它串成一个数字:
42500
发布于 2022-11-27 20:30:07
这在本机JSON.stringify
实现中目前是不可能的。随着 proposal的采用,它将成为可能,它还包括一个用于非有损序列化的助手。
你会用它作为
const text = JSON.stringify(value, (key, val) => {
if (val instanceof math.bignumber) return JSON.rawJSON(val.toString())
else return val;
});
console.log(text);
发布于 2022-11-27 20:28:56
OP在正确的轨道上,这应该很好:
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)));
而不是TS。
https://stackoverflow.com/questions/74593342
复制相似问题