bignumber.js modulo negative returns incorrect value

168 Views Asked by At

The following code should return 16. However, it returns -1.

import BigNumber from 'bignumber.js';
const a = BigNumber(-1)
const p = BigNumber(17)

console.log(a.modulo(p))

The documentation does not provide clarity on how to handle this situation.

1

There are 1 best solutions below

0
Soubriquet On BEST ANSWER

In BigNumber.js, the modulo operation returns a value with the same sign as the dividend (in this case, -1). Therefore, when you calculate -1 modulo 17, it will return -1.

If you want to get the positive remainder, you can use this workaround:

import BigNumber from 'bignumber.js';

const a = BigNumber(-1);
const p = BigNumber(17);

const result = a.modulo(p).plus(p).modulo(p);

console.log(result.toString()); // "16"

This code adds the modulus p to the result of the initial modulo operation, and then takes the modulo again with respect to p. This ensures that the final result is positive and in the desired range [0, p).