I'm working on an auction feature in my DApp and having problems correctly adding together two WEI
values.
The contract stores two important values:
1. A minBidIncrement
variable – which I've set to 0.1 ETH
, and
2. A highestBidAmount
variable – which stores the highest bid anyone has made to date.
Thus, if the last highest bid was say 2.5 ETH
, I want to make sure the next allowable bid would be at least that plus the minBidIncrement
, meaning it should be:
2.5 ETH + 0.1 ETH
which equals 2.6 ETH
.
Its pretty straight forward stuff.
So I'm doing this:
let minNextBid = highestBidAmount + minBidIncrement;
but what I get from that is some crazy huge value which causes my Dapp to freak out and Metamask to give me errors.
Here's what's happening underneath the hood:
–highestBidAmount
comes back as 100000000000000000
–minBidIncrement
also comes back as 100000000000000000
(both of those are fine cause they're 18 decimal places, which means they're really 0.1 ETH
)
So next when I set my minNextBid
, I'm basically doing 100000000000000000
+ 100000000000000000
, but that yields: 100000000000000000100000000000000000
And when I then convert that to ETH, I get this value: 100000000000000000.1
which isn't at all what I was expecting to get. What I was expecting to get was 0.2 ETH
, but I get that astronomical value instead.
So what's happening here? What am I doing wrong?
What's the right way to do this?
Best Answer
You are concatenating strings in JavaScript.
Here is what happens:
OUTPUTS:
hello
. You are using integers as strings.Therefore you need to convert your variables to int before adding them.
Here is an example:
Sidenote: Don't change the 10 it has nothing to do with decimal places. It's the radix used.
Do that with both variables:
Now add them:
Now you are adding integers so it results in:
200000000000000000