简体   繁体   English

是否可以使用web3.js从Solidity获取uint256值

[英]Is it possible to get uint256 value from Solidity using web3.js

So the question is pretty simple. 所以问题很简单。 I am calling contract method that returns uint256 value. 我正在调用返回uint256值的合同方法。 Is it possible to get that value in JavaScript at all? 是否有可能完全在JavaScript中获得该价值? As far as I understand JavaScript can't work with big numbers and the solution would be to make new contract that returns data as string? 据我了解,JavaScript不能与大数一起使用,解决方案是制定新的合同,将数据返回为字符串? Right now I am getting a value that simply cuts a lot of zeros :) 现在,我得到的值只是减少了很多零:)

Web3 returns primitive data types (including uint ) as strings. Web3返回原始数据类型(包括uint )作为字符串。 If you try to parse it into javascript native number with something like parseInt , it will fail. 如果您尝试使用parseInt内容将其解析为javascript本地数字,则它将失败。

To work with the big numbers received via web3, you have to use library which can handle them. 要处理通过web3收到的大量数字,您必须使用可以处理它们的库。 One such library is BigNumber.JS https://github.com/MikeMcl/bignumber.js/ BigNumber.JS https://github.com/MikeMcl/bignumber.js/

So you can then use it like this: 因此,您可以像这样使用它:

let result = BigNumber(await bigNumber.methods.getNum1().call());

and use math operations implemented by BigNumber.js 并使用BigNumber.js实现的数学运算

result = result.plus("99999999999999999999999999999999999999");

note that if you then simply try to use the result value itself 请注意,如果您只是尝试使用结果值本身

console.log(result);

you will get result like this 你会得到这样的结果

  BigNumber {
    s: 1,
    e: 38,
    c: [ 10000000213, 12312312312312, 45465777775431 ] }

Therefore you will probably want to cast it to the string in the end 因此,您可能最终希望将其转换为字符串

console.log(result.toString());

to get result in readable form, like: 以可读形式获取结果,例如:

1.00000002131231231231231245465777775431e+38

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM