In the Create-React box from Truffle, why do we retrieve a uint value from a function call with "result.c[0]" instead of "result"? What's the c[0]?


This strikes me as bad code. When a number is returned from a contract, it's of type BigNumber in JavaScript. It can be converted to a string with .toString().

It can also be converted to a number via .toNumber(), but be careful about loss of precision. The reason BigNumber is used in the first place is because JavaScript can't handle large numbers. It's generally best to keep the number in BigNumber or string form (or perhaps hex).

  • 1
    Thanks! I defined storageValue as a string in the constructor using storageValue: ' ' then I added a function to the chain: .then((result) =>{ return result.toString() right before calling setState. One more question, I'm still not sure what number.c[0] does, can you tell me? – Robin Feb 26 '18 at 7:22

In regard to result.c[0]

result is a BigNumber object in this case — rather counterintuitively I suspect you thought you would get back a single uint (who wouldn’t!), but because uint256 is larger than JS can handle the value is wrapped in a BigNumber object, what you’ve accessed (via result.c) is the coefficient which returns an array, the first index being the value, and the second index is the exponent.

Credit to rxdizzle for the explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.