[英]How to do basic arithmetic in Truffle testing using web3.js
I'm currently using Truffle to test smart contracts, but having difficulty with basic arithmetics.我目前正在使用 Truffle 来测试智能合约,但在基本算术方面有困难。
If I try to add two numbers:如果我尝试添加两个数字:
const firstNumber = web3.utils.toWei('1', 'ether'); // 1000000000000000000
const sum = firstNumber + 100
The result is like when two strings are attached 1000000000000000000100
.结果就像附加两个字符串
1000000000000000000100
。
I tried converting firstNumber.toString()
or using const { toBN } = web3.utils;
我尝试转换
firstNumber.toString()
或使用const { toBN } = web3.utils;
but all have the same result.但都有相同的结果。
I tried using add
or mul
like some examples here , but my Truffle simply says those methods don't exist.我试着像这里的一些例子一样使用
add
或mul
,但我的 Truffle 只是说这些方法不存在。
I'm using Truffle v5.3.14 (core: 5.3.14)
and Web3.js v1.4.0
.我正在使用
Truffle v5.3.14 (core: 5.3.14)
和Web3.js v1.4.0
。
'1' is a string so you will receive string from .toWei . '1' 是一个字符串,因此您将收到来自.toWei 的字符串。 You can convert String to BN and use .add .
您可以将 String 转换为 BN 并使用.add 。 For example:
例如:
const firstNumber = web3.utils.toWei('1', 'ether'); // 1000000000000000000
const sum = web3.utils.toBN(firstNumber).add(web3.utils.toBN('100')).toString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.