json-bignum

2020-01-14

json-bignum

Node.js JSON replacement which handles 64-bit integers and arbitrary-precision decimals.

json-bignum

Node.js JSON replacement which handles 64-bit integers and arbitrary-precision decimals. It is a modified version of Douglas Crockford's JSON library. Although it can handle 64-bit integers and arbitrary-precision decimals, it is slower than the built-in JSON functions.

Install

$ npm install json-bignum

Usage

parse()

var bignumJSON = require('json-bignum');

var obj = bignumJSON.parse('{ "decimal": -9223372036854775807.4237482374983253298159 }');

stringify()

var bignumJSON = require('json-bignum');

var obj = {
    bigint: new bignumJSON.BigNumber('92233720368547758074237482374983253298159'),
    decimal: new bignumJSON.BigNumber('-9223372036854775807.4237482374983253298159'),
};

console.log(bignumJSON.stringify(obj));

BigNumber

The BigNumberclass simply stores the number as a string. It does not support arithmetic, but if you need that here are some excellent libraries.

  • BigDecimal.js: a literal port of Java's BigIntegerand BigDecimalclasses.
  • bigint: Big integer arithmetic using GMP.
  • bignum: Big integer arithmetic using OpenSSL.
// example using BigDecimal.js

var bignumJSON = require('json-bignum');
var bigdecimal = require('bigdecimal');

var jsonStr = '{"normal":-922337203.234,"big":-9223372036854775807.4237482374983253298159}';
var jsonObj = bignumJSON.parse(jsonStr);

var a = new bigdecimal.BigDecimal(jsonObj.normal.toString());
var b = new bigdecimal.BigDecimal(jsonObj.big.toString());
var sum = a.add(b);

jsonObj.sum = new bignumJSON.BigNumber(sum.toString());

console.log(bignumJSON.stringify(jsonObj));

Caveats

It is not recommended to mix calls to JSONand bignumJSON. For example, JSON.stringify()does not know how to parse BigNumber.

Benchmark

Below shows the result of the benchmark on my machine.

$ node benchmark.js
10000 calls of JSON.parse():                                   26.746847 ms
10000 calls of JSON.stringify():                               20.824071 ms
10000 calls of bignumJSON.parse() with bignums in JSON:        221.945307 ms
10000 calls of bignumJSON.parse() without bignums in JSON:     150.626292 ms
10000 calls of bignumJSON.stringify() with bignums in JSON:    64.166056 ms
10000 calls of bignumJSON.stringify() without bignums in JSON: 61.860016 ms

以上是 json-bignum 的使用教程帮助文档。


上一篇:@floydophone/ts-node-dev
下一篇:simple-lastfm
相关教程
关注微信

扫码加入 JavaScript 社区

相关文章

首次访问,需要验证
微信扫码,关注即可
(仅需验证一次)

欢迎加入 JavaScript 社区

号内回复关键字:

回到顶部