How to use bignumber.js

Comprehensive bignumber.js code examples:

How to use bignumber.js.set:

310
311
312
313
314
315
316
317
318

//----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------


// The default values below must be integers within the inclusive ranges stated.
// The values can also be changed at run-time using BigNumber.set.

// The maximum number of decimal places for operations involving division.
DECIMAL_PLACES = 20,                     // 0 to MAX

How to use bignumber.js.prototype:

374
375
376
377
378
379
380
381
382
383

// The maximum number of significant digits of the result of the exponentiatedBy operation.
// If POW_PRECISION is 0, there will be unlimited significant digits.
POW_PRECISION = 0,                       // 0 to MAX

// The format specification used by the BigNumber.prototype.toFormat method.
FORMAT = {
  prefix: '',
  groupSize: 3,
  secondaryGroupSize: 0,

How to use bignumber.js.max:

555
556
557
558
559
560
561
562
563
564
	logger.debug('PP> worker.sent = %s', worker.sent.toString(10));
	worker.balanceChange = BigNumber.min(worker.balance, worker.sent).multipliedBy(new BigNumber(-1));
	logger.debug('PP> worker.balanceChange = %s', worker.balanceChange.toString(10));
} else {
	logger.debug('PP> Worker %s have not reached minimum payout threshold %s', w, minPayment.toString(10));
	worker.balanceChange = BigNumber.max(toSend.minus(worker.balance), new BigNumber(0));
	logger.debug('PP> worker.balanceChange = %s', worker.balanceChange.toString(10));
	worker.sent = new BigNumber(0);
	logger.debug('PP> worker.sent = %s', worker.sent.toString(10));
	if (worker.balanceChange > 0) {

How to use bignumber.js.min:

236
237
238
239
240
241
242
243
244
245
const tokenAPercentIncrease = amountA.mul(totalSupply).div(reserve0);
const tokenBPercentIncrease = amountB.mul(totalSupply).div(reserve1);

const bnTokenAPercentIncrease = new BigNumber(ethers.utils.formatUnits(tokenAPercentIncrease));
const bnTokenBPercentIncrease = new BigNumber(ethers.utils.formatUnits(tokenBPercentIncrease));
const minimum = BigNumber.min(bnTokenAPercentIncrease, bnTokenBPercentIncrease);
const formattedMininum = minimum.toFormat();
const formattedLiquidity = ethers.utils.formatUnits(liquidity);

expect(formattedLiquidity).to.equal(formattedMininum);

How to use bignumber.js.random:

30
31
32
33
34
35
36
37
38
39
40
}


// Override
baseGeneration.generateUniform = function (test, options, max) {
  max = determineMax(test, options.party_count, options.integer_digits, options.decimal_digits, max);
  var wholeNum = BigNumber.random().times(max).floor();
  var deciNum = wholeNum.div(new BigNumber(10).pow(options.decimal_digits));
  return Math.random() < 0.5 ? deciNum : deciNum.times(-1);
};
baseGeneration.generateNonZeroUniform = function (test, options, max) {

How to use bignumber.js.default:

120
121
122
123
124
125
126
127
128
129
    const index = data.columns.findIndex(col => col.key === key);
    // statisticsRow[key] = {
    //   formula: `SUM(${getArea(index, index + 1, recordRowStart, recordRowEnd)})`,
    //   result: BigNumber.sum(...records.map(r => new BigNumber((r[key] as any) || 0))).toNumber()
    // }
    statisticsRow[key] = bignumber_js_1.default.sum(...records.map(r => new bignumber_js_1.default(r[key] || 0))).toNumber();
}
if (statistics.length > 0) {
    worksheet.addRow(statisticsRow, 'i'); // 添加Footer row
}

How to use bignumber.js.isBigNumber:

212
213
214
215
216
217
218
219
220
221
222
223
            v,          // The member value.
            length,
            mind = gap,
            partial,
            value = holder[key],
            isBigNumber = value != null && (value instanceof BigNumber || BigNumber.isBigNumber(value));


// If the value has a toJSON method, call it to obtain a replacement value.


        if (value && typeof value === 'object' &&

How to use bignumber.js.minimum:

944
945
946
947
948
949
950
951
952
953
 * 返回给定键的最小值
 */
min(key) {
    // 获取值
    const nums = getNums.call(this, key)
    return nums.length ? BigNumber.minimum(...nums).toNumber() : 0
}

/**
 * 方法确定集合中是否存在给定键

How to use bignumber.js.maximum:

935
936
937
938
939
940
941
942
943
944
 * 返回给定键的最大值
 */
max(key) {
    // 获取值
    const nums = getNums.call(this, key)
    return nums.length ? BigNumber.maximum(...nums).toNumber() : 0
}

/**
 * 返回给定键的最小值

How to use bignumber.js.sum:

115
116
117
118
119
120
121
122
123
124
if (tokenId == null) {
  const map = {};
  result.forEach(info => {
    const address = info.holder;
    if (map[address] === undefined) map[address] = 0;
    map[address] = BigNumber.sum(new BigNumber(map[address]), new BigNumber(info.amount)).toFixed();
  })
  holders = Object.keys(map).map(address => ({
    address: address,
    amount: map[address]

How to use bignumber.js.config:

206
207
208
209
210
211
212
213
214
215
 */
function get_dx_slippage(currentTick, tickSpacing, sqrtPriceX96, liquidity, tokenDecimals) {
    const base = new BigNumber(1.0001);
    const decimalFactor = new BigNumber(10).pow(tokenDecimals);
    let dx = new BigNumber(0);
    BigNumber.config({ POW_PRECISION: 10 });
    const _96bits = new BigNumber(2).pow(new BigNumber(96));
    let currSqrtPrice = new BigNumber(sqrtPriceX96).div(_96bits); 
    let currTick = getNextLowerTick(Number(currentTick), tickSpacing);

How to use bignumber.js.BigNumber:

329
330
331
332
333
334
335
336
337
338
339
 More info: https://en.bitcoin.it/wiki/Target
 */


exports.bignumFromBitsBuffer = function (bitsBuff) {
  var numBytes = bitsBuff.readUInt8(0);
  var bigBits = new BigNumber("0x" + bitsBuff.slice(1).toString("hex"));
  var target = bigBits.times(
    new BigNumber(2).pow(new BigNumber(8).times(numBytes - 3))
  );
  return target;