Numbers

In Solidity, there are several types of numbers that can be used as state variables or function parameters. Some of the most common ones are:

  1. uint: an unsigned integer, which can only store non-negative values. It can be of various sizes, such as uint8, uint16, uint32, etc., up to uint256.

  2. int: a signed integer, which can store both positive and negative values. It can also be of various sizes, such as int8, int16, int32, etc., up to int256.

  3. fixed point numbers: numbers with a decimal point, which can have a fixed number of decimal places. They are represented by the types fixed and ufixed, followed by the number of decimal places, such as fixed256x18.

  4. byte: a single byte of data, which can store values between 0 and 255.

  5. bytes: a dynamic array of bytes, which can store any number of bytes.

Here's an example of a Solidity function that uses some of these types:


function calculateAverage(uint[] memory numbers) public returns (fixed256x18) {
    uint sum = 0;
    for (uint i = 0; i < numbers.length; i++) {
        sum += numbers[i];
    }
    return fixed256x18(sum) / fixed256x18(numbers.length);
}

In this example, the function takes an array of unsigned integers as a parameter, and returns a fixed point number (with 18 decimal places) representing the average of the numbers in the array. The function first calculates the sum of the numbers using an unsigned integer variable, and then divides the sum by the length of the array using fixed point division.

Last updated