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?

  • Please show us your actual code. We can't debug nor run your sayings. You never mention it but it looks like a javascript bug to concatenate instead of an addition. – Ismael Sep 14 '19 at 5:12
  • In case this fixed your problem please mark it as an answer. – Niklas Feurstein Sep 14 '19 at 11:47

You are concatenating strings in JavaScript.

Here is what happens:

var test = "he";
var test2 = "llo";

OUTPUTS: hello. You are using integers as strings.

Therefore you need to convert your variables to int before adding them.

Here is an example:

highestBidAmount = parseInt(highestBidAmount, 10);

Sidenote: Don't change the 10 it has nothing to do with decimal places. It's the radix used.

Do that with both variables:

minBidIncrement = parseInt(minBidIncrement, 10);

Now add them:

let minNextBid = highestBidAmount + minBidIncrement;

Now you are adding integers so it results in: 200000000000000000

| improve this answer | |
  • That was right on man - I was concatenatin'! Thanks for setting me straight! – Sirab33 Sep 14 '19 at 21:40

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.