🎓 A1Learner
🔍
0 of 50 lessons completed

Solidity Arithmetic

Arithmetic is doing maths with the operators +, -, *, /, and %. Solidity does this maths on whole numbers, so division drops any fraction.

Addition and subtraction return results

Two functions do the two simplest sums. Each one returns its result to the caller.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract AddSubtract {
    function add(uint256 a, uint256 b) public returns (uint256) {
        return a + b;
    }

    function subtract(uint256 a, uint256 b) public returns (uint256) {
        return a - b;
    }
}

Multiplication and division return results

The * operator multiplies and the / operator divides. Division drops the fraction, so 7 / 2 gives 3.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract MultiplyDivide {
    function multiply(uint256 a, uint256 b) public returns (uint256) {
        return a * b;
    }

    function divide(uint256 a, uint256 b) public returns (uint256) {
        return a / b;
    }
}

Remainder returns what is left over

The % operator gives the leftover after division. For 7 % 2, the leftover is 1.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract RemainderBox {
    function remainder(uint256 a, uint256 b) public returns (uint256) {
        return a % b;
    }
}

Example

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;

contract Calculator {
    function add(uint256 a, uint256 b) public returns (uint256) {
        return a + b;
    }

    function subtract(uint256 a, uint256 b) public returns (uint256) {
        return a - b;
    }

    function multiply(uint256 a, uint256 b) public returns (uint256) {
        return a * b;
    }

    function divide(uint256 a, uint256 b) public returns (uint256) {
        return a / b;
    }

    function remainder(uint256 a, uint256 b) public returns (uint256) {
        return a % b;
    }
}

Key points

  • Add: the + operator adds two numbers together.
  • Subtract: the - operator takes one number away from another.
  • Multiply: the * operator multiplies two numbers.
  • Divide: the / operator divides and drops any fraction from the result.
  • Remainder: the % operator returns what is left over after division.
  • Return: an arithmetic function sends its result back with the return word.

In this example, one Calculator contract holds all five arithmetic functions together. The add function returns a + b and subtract returns a - b. The multiply function returns a * b. The divide function returns a / b and drops the fraction, so 7 / 2 is 3. The remainder function returns a % b, so 7 % 2 is 1.

Note

Solidity integer maths gives whole number results only, with no fractions kept.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Remix IDE

Exercise

In a Solidity contract, what does 7 / 2 return?