9

I'm trying to check whether the amount send by an account is even. For now, I have the code below but when I send only 1 ETH, it doesn't not come back. Seems odd (pun intended :p )

uint amount;
amount = msg.value;
if (amount % 2 != 0  ) {
      msg.sender.send(amount);
    return;
}

1 Answer 1

8

You are checking if 1000000000000000000 divided by 2 has a remainder of 0 which it has.

If you want to check if only whole ethers are send you need to check if amount modulo 1000000000000000000 does not equal 0.

So your code would be:

uint amount;
amount = msg.value;
if (amount % 1 ether != 0  ) {
      msg.sender.send(amount);
    return;
}
3
  • Your 1 ether is represented in your contract code as 1000000000000000000 wei - see ether.fund/tool/converter . The answer by Mick de Graaf should work. Apr 9, 2016 at 16:09
  • Thanks Mick ! So if I want to check if the amount are only mutliples of, let's say 100, i would have to write (amout % 100 ether != 0), correct ?
    – ChrisH127
    Apr 9, 2016 at 16:11
  • With that condition you are checking if it is not a 0 multitude of 1 ether and it gets send back if not. To reverse this behavior use == instead of !=. Apr 11, 2016 at 7:28

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.