[Ethereum] how to deal with large numbers in Ethereum

bignumbersolidity

I am confused with the use of large numbers in solidity, ethereum. I have some doubts please help me with them.

1) I am not able to represent the value of p using p.toNumber() but can represent it when I use p.toString(). where p is

uint256 p = msg.value

2) myToken.transfer(acc[3], 100000000000000000000, {from:acc[0]})

I am not not able to transfer a large number of tokens like in the above
it says { Error: invalid number value (arg="_value", coderType="uint256", value=100000000000000000000)

3)not able to set the initial supply with

module.exports = function(deployer) {
deployer.deploy(DappToken, 1000000000000000000000)

but when I use "" it works, I am not able to understand the reason behind any of these but I think it's the same, please help

I assure you that the rest of the code is fine and works well for small numbers.

thanks.

Best Answer

In Javascript, the maximum safe integer is 2^53-1.

So you should generally avoid using numbers like 100000000000000000000.

For example, in your code, you should change this:

myToken.transfer(acc[3], 100000000000000000000, {from:acc[0]})

To this:

myToken.transfer(acc[3], "100000000000000000000", {from:acc[0]})

In addition to that, the usage of toNumber() is also unsafe, as you have noticed yourself.

When you call from the off-chain an on-chain function which returns uint256, you get a BigNumber object. If this object represents a number smaller than Number.MAX_SAFE_INTEGER, then it is safe to use toNumber() on it. But since you do not know that for sure, you should avoid using toNumber().

Also, please note that it is better to use toFixed() than toString(), because the latter may return the scientific notation of the number (e.g. 1+e18), which may give you unexpected problems when you later use it in other contexts.