Open In App

Fixed Point Numbers in Solidity

Last Updated : 18 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Fixed-point numbers represent fractional values (like 3.14 or 0.001) with a fixed number of digits after the decimal point. Unlike floating-point numbers, which can vary in precision and introduce rounding errors, fixed-point numbers maintain a consistent level of precision. This article focuses on discussing the fixed point numbers in Solidity.

What are Fixed Point Numbers?

Fixed-point numbers represent fractional values without relying on floating-point arithmetic, which can be inefficient and error-prone in smart contracts. Solidity doesn't natively support fixed-point numbers like it does integers, but developers can simulate their behavior using integer arithmetic.

  1. Precision: Avoids the inaccuracies associated with floating-point numbers.
  2. Performance: Integer operations are faster and cheaper in terms of gas usage.
  3. Safety: Reduces the risk of unexpected behaviors in financial calculations, which is vital in smart contracts.

What are Fixed Point Operators?

Fixed-point arithmetic operations are essential for handling fractional values in Solidity smart contracts. These operations use integer arithmetic to simulate the behavior of fixed-point numbers. Here’s a closer look at the basic fixed-point operators:

  1. Addition: Adds two fixed-point numbers by simply summing them up.
  2. Subtraction: Subtracts one fixed-point number from another while ensuring no underflow occurs.
  3. Multiplication: Multiplies two fixed-point numbers, then scales the result down to maintain the correct precision.
  4. Division: Divides one fixed-point number by another, scaling the numerator up to preserve precision before the division.

Fixed vs Floating Point Numbers

Aspect

Fixed Point Numbers

Floating Point Numbers

Definition

Fixed-point numbers represent fractional values using integer arithmetic. They are scaled by a fixed factor (e.g., 10^2 for two decimal places).

Floating-point numbers use a different representation that can support a wide range of values by using a variable exponent.

Rounding Errors

This approach ensures that all arithmetic operations remain precise and deterministic, avoiding rounding errors.

This can lead to rounding errors and precision issues, which are particularly problematic in financial applications.

Precision

Fixed-point numbers maintain exact precision for fractional values.

Floating-point numbers can introduce rounding errors.

Performance

Fixed-point arithmetic is faster and more efficient in terms of gas usage.

Floating-point arithematic is slow compared to fixed-point arithematic.

Determinism

Fixed-point arithmetic ensures predictable and repeatable results.

Floating-point operations can produce different results on different platforms.

Conversion

Converting between integers and fixed-point numbers involves scaling operations. Here's how it can be done:

To Fixed Point

To convert an integer to a fixed-point number, multiply it by the scaling factor. To add a fractional part, simply add it to the scaled integer.

From Fixed Point

To convert a fixed-point number back to its integer and fractional parts, divide the number by the scaling factor for the integer part and take the modulus for the fractional part.

Below is the Solidity program to implement conversion:

Solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract FixedPointStruct {
    uint256 constant SCALE = 10**2;

    struct FixedPoint {
        uint256 integer;
        uint256 fraction;
    }

    function toFixedPoint(uint256 integer, uint256 fraction) public pure returns (FixedPoint memory) {
        return FixedPoint(integer, fraction);
    }

    function fromFixedPoint(FixedPoint memory fixedPoint) public pure returns (uint256, uint256) {
        return (fixedPoint.integer, fixedPoint.fraction);
    }
}

Here below you can see the one by one step for execution this code with deployed, input and output screenshots.

Overflow in Conversion

Handling overflows and underflows is crucial in Solidity. Before version 0.8.0, developers relied on libraries like SafeMath for protection. From version 0.8.0 onwards, Solidity includes built-in checks for these issues.

Implementing Fixed Point Numbers Using Struct in Solidity

Using a struct can improve readability and manageability when dealing with fixed-point numbers. Here’s an example:

Solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract FixedPointStruct {
    uint256 constant SCALE = 10**2;

    struct FixedPoint {
        uint256 integer;
        uint256 fraction;
    }

    function toFixedPoint(uint256 integer, uint256 fraction) public pure returns (FixedPoint memory) {
        return FixedPoint(integer, fraction);
    }

    function fromFixedPoint(FixedPoint memory fixedPoint) public pure returns (uint256, uint256) {
        return (fixedPoint.integer, fixedPoint.fraction);
    }
}

Deploying Contract:

file
Deploying Contract

Input Fields:

file
Empty Input Fields
file
Example Input Fields

Output:

file
Output

Addition and Subtraction

Using fixed-point arithmetic for addition and subtraction ensures precise results. Here’s how it can be implemented:

Solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract FixedPointStruct {
    uint256 constant SCALE = 10**2;

    struct FixedPoint {
        uint256 integer;
        uint256 fraction;
    }

    function add(FixedPoint memory a, FixedPoint memory b) public pure returns (FixedPoint memory) {
        uint256 newFraction = a.fraction + b.fraction;
        uint256 carry = newFraction / SCALE;
        newFraction = newFraction % SCALE;

        uint256 newInteger = a.integer + b.integer + carry;

        return FixedPoint(newInteger, newFraction);
    }

    function subtract(FixedPoint memory a, FixedPoint memory b) public pure returns (FixedPoint memory) {
        require(a.integer > b.integer || (a.integer == b.integer && a.fraction >= b.fraction), "Subtraction underflow");

        uint256 newFraction;
        uint256 borrow;

        if (a.fraction >= b.fraction) {
            newFraction = a.fraction - b.fraction;
        } else {
            borrow = 1;
            newFraction = a.fraction + SCALE - b.fraction;
        }

        uint256 newInteger = a.integer - b.integer - borrow;

        return FixedPoint(newInteger, newFraction);
    }
}

Deployed Contract:

file
Deployed Contract

Input Fields:

file
Empty Input Fields
file
Example Input Fields

Output:

file
Output

Multiplication and Division

Multiplication and division in fixed-point arithmetic require scaling adjustments to maintain precision:

Solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract FixedPointStruct {
    uint256 constant SCALE = 10**2;

    struct FixedPoint {
        uint256 integer;
        uint256 fraction;
    }

function multiply(FixedPoint memory a, FixedPoint memory b) public pure returns (FixedPoint memory) {
        uint256 integerPart = (a.integer * b.integer) * SCALE;
        uint256 fractionPart1 = (a.integer * b.fraction);
        uint256 fractionPart2 = (b.integer * a.fraction);
        uint256 fractionPart3 = (a.fraction * b.fraction) / SCALE;

        uint256 totalFraction = fractionPart1 + fractionPart2 + fractionPart3;
        uint256 carry = totalFraction / SCALE;
        totalFraction = totalFraction % SCALE;

        uint256 resultInteger = integerPart + carry;

        return FixedPoint(resultInteger, totalFraction);
    }

    function divide(FixedPoint memory a, FixedPoint memory b) public pure returns (FixedPoint memory) {
        require(b.integer != 0 || b.fraction != 0, "Division by zero");

        uint256 numerator = a.integer * SCALE + a.fraction;
        uint256 denominator = b.integer * SCALE + b.fraction;

        uint256 result = (numerator * SCALE) / denominator;

        return FixedPoint(result / SCALE, result % SCALE);
    }
}

Deployed Contract:

file
Deployed Contract

Input Field:

file
Empty Input Fields
file
Example Input Fields

Output:

file
Output

Step-by-Step Guide to Running the Contract in Remix IDE

1. Open Remix IDE

Open your web browser and go to Remix IDE.

2. Create a New File

  1. In the left sidebar, you'll see a file explorer. Click on the + icon to create a new file.
  2. Name the new file FixedPointArithmeticStruct.sol.

3. Paste the Solidity Code

Copy the following Solidity code and paste it into the newly created FixedPointArithmeticStruct.sol file:

Solidity
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract FixedPointStruct {
    uint256 constant SCALE = 10**2;

    struct FixedPoint {
        uint256 integer;
        uint256 fraction;
    }

    function toFixedPoint(uint256 integer, uint256 fraction) public pure returns (FixedPoint memory) {
        return FixedPoint(integer, fraction);
    }

    function fromFixedPoint(FixedPoint memory fixedPoint) public pure returns (uint256, uint256) {
        return (fixedPoint.integer, fixedPoint.fraction);
    }

    function add(FixedPoint memory a, FixedPoint memory b) public pure returns (FixedPoint memory) {
        uint256 newFraction = a.fraction + b.fraction;
        uint256 carry = newFraction / SCALE;
        newFraction = newFraction % SCALE;

        uint256 newInteger = a.integer + b.integer + carry;

        return FixedPoint(newInteger, newFraction);
    }

    function subtract(FixedPoint memory a, FixedPoint memory b) public pure returns (FixedPoint memory) {
        require(a.integer > b.integer || (a.integer == b.integer && a.fraction >= b.fraction), "Subtraction underflow");

        uint256 newFraction;
        uint256 borrow;

        if (a.fraction >= b.fraction) {
            newFraction = a.fraction - b.fraction;
        } else {
            borrow = 1;
            newFraction = a.fraction + SCALE - b.fraction;
        }

        uint256 newInteger = a.integer - b.integer - borrow;

        return FixedPoint(newInteger, newFraction);
    }

    function multiply(FixedPoint memory a, FixedPoint memory b) public pure returns (FixedPoint memory) {
        uint256 integerPart = (a.integer * b.integer) * SCALE;
        uint256 fractionPart1 = (a.integer * b.fraction);
        uint256 fractionPart2 = (b.integer * a.fraction);
        uint256 fractionPart3 = (a.fraction * b.fraction) / SCALE;

        uint256 totalFraction = fractionPart1 + fractionPart2 + fractionPart3;
        uint256 carry = totalFraction / SCALE;
        totalFraction = totalFraction % SCALE;

        uint256 resultInteger = integerPart + carry;

        return FixedPoint(resultInteger, totalFraction);
    }

    function divide(FixedPoint memory a, FixedPoint memory b) public pure returns (FixedPoint memory) {
        require(b.integer != 0 || b.fraction != 0, "Division by zero");

        uint256 numerator = a.integer * SCALE + a.fraction;
        uint256 denominator = b.integer * SCALE + b.fraction;

        uint256 result = (numerator * SCALE) / denominator;

        return FixedPoint(result / SCALE, result % SCALE);
    }
}
file
FixedPointArithmatic.sol Contract Code

4. Compile the Contract

  1. Select the Solidity Compiler tab on the left sidebar (it looks like a "compiler" icon).
  2. Ensure the compiler version is set to 0.8.0 or higher (since your contract uses pragma ^0.8.0).
  3. Click the Compile FixedPointArithmetic.sol button. You should see a green checkmark if the compilation is successful.

5. Deploy the Contract

  1. Go to the Deploy & Run Transactions tab (it looks like an "Ethereum" icon).
  2. Select Remix VM (Cancun) from the Environment dropdown. This setting runs a local blockchain in your browser.
  3. Ensure that the FixedPointArithmetic contract is selected in the Contract dropdown.
  4. Click the Deploy button.

6. Interact with the Deployed Contract

  • After deploying, you will see the deployed contract instance under the Deployed Contracts section at the bottom of the Deploy & Run Transactions tab.
  • Expand the deployed contract instance to see the available functions.

7. Test the Functions

  • toFixedPoint(3, 14):
    • Input: 3, 14
    • Output: FixedPoint = { integer: 3, fraction: 14 }
  • fromFixedPoint(FixedPoint(3, 14)):
    • Input: [3, 14]
    • Output: { integer: 3, fraction: 14 }
  • add(FixedPoint(1, 50), FixedPoint(2, 75)):
    • Input: [1, 50], [2, 75]
    • Output: FixedPoint = { integer: 4, fraction: 25 }
  • subtract(FixedPoint(5, 20), FixedPoint(3, 50)):
    • Input: [5, 20], [3, 50]
    • Output: FixedPoint = { integer: 1, fraction: 70 }
  • multiply(FixedPoint(2, 50), FixedPoint(3, 25)):
    • Input: [2, 50], [3, 25]
    • Output: FixedPoint = { integer: 8, fraction: 12 }
  • divide(FixedPoint(5, 0), FixedPoint(2, 50)):
    • Input: [5, 0], [2, 50]
    • Output: FixedPoint = { integer: 2, fraction: 0 }

8. Output Screenshots

Deploy The FixedPointArithmeticStruct.sol:

file
Deployed FixedPointArithmeticStruct.sol Contract

Input Fields:

file
Empty Input Fields
file
Example Input Fields

Output of All Example Inputs:

file
Outputs

All Transaction Log - Deployed Contract and Deployed Functions:

file
All Transactions Log

1. Overflow and Underflow Protection

Handling overflows and underflows is crucial in Solidity. Before version 0.8.0, developers relied on libraries like SafeMath for protection. From version 0.8.0 onwards, Solidity includes built-in checks for these issues.

2. Libraries for Fixed Point Arithmetic

Several libraries provide robust support for fixed-point arithmetic in Solidity. For example, ABDKMath64x64 offers functions for various mathematical operations on fixed-point numbers, using 64 bits for both the integer and fractional parts.

3. Use Cases in Smart Contracts

Fixed-point arithmetic is particularly useful in:

  • Token Contracts: Managing token balances, transfers, and exchanges with precision.
  • Decentralized Finance (DeFi): Performing financial computations like interest calculations, lending, and borrowing.
  • Stablecoins: Maintaining stablecoin pegs through precise arithmetic operations.

4. Gas Optimization

Gas optimization is a critical aspect of smart contract development. Fixed-point arithmetic can reduce gas costs compared to floating-point arithmetic. However, developers need to balance precision and gas efficiency carefully.

Conclusion

Fixed-point numbers are essential for handling fractional values accurately and efficiently in Solidity smart contracts. By mastering fixed-point arithmetic, developers can create more robust and reliable smart contracts, particularly for financial applications. As the Ethereum ecosystem evolves, tools and libraries for fixed-point arithmetic will continue to improve, offering even better support for developers.


Next Article
Article Tags :

Similar Reads