Skip to content

How do I mimic Solidity/EVM signed modulo arithmetic with BigNumber? #1408

Answered by ricmoo
PaulRBerg asked this question in Q&A
Discussion options

You must be logged in to vote

That is correct. :)

The ethers BigNumber always returns a positive number in the range [0, N). Solidity (and EVM's SMOD) uses the C fmod-style method, which returns a value with the same sign as value.

If you want to mimic Solidity's behaviour, you can use a method similar to:

function solidityMod(k, N) {
    let result = k.mod(N);
    if (k.isNeg()) { result = result.sub(N); }
    return result;
}

Does that make sense?

Replies: 3 comments 3 replies

Comment options

You must be logged in to vote
3 replies
@PaulRBerg
Comment options

@PaulRBerg
Comment options

@ricmoo
Comment options

Answer selected by ricmoo
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #1402 on March 27, 2021 02:14.