Solidity – How to Convert Hex Numbers Using JavaScript?

javascriptsolidity

var contract = await tronWeb.contract().at(contractAddress);
var result = await contract.getPlayerDeposit("").call();

Output:
I got in array:
(4) [Array(1), Array(1), Array(1), Array(1)]
0: Array(1)
0: v {_hex: "0x00", _ethersType: "BigNumber"}
length: 1
proto: Array(0)
1: Array(1)
0: v
_hex: "0x5f887761"
_ethersType: "BigNumber"
proto: Object
length: 1
proto: Array(0)
2: [v]
3: [v]
length: 4
proto: Array(0)

How to convert hex number? I'm using javascript to retrieve data from contract?

Best
Chris

Best Answer

I assume you want to convert the BigNumber into a normal number, you can do that by:

result[0].toNumber()

But keep in mind that JavaScript's Number is a 64 bit number, so the uint256 in your solidity contract might not always be shrinked down to 64 bits.

A safer way to to that is to keep the number in String, if you don't want to do any additions or substractions on it.

result[0].toString()

If the number is not going to be very big, you can keep it uint32 in your contract, that automatically makes the ethers.js to convert it into a JavsScript Number by default.