Fixed Point Numbers in Solidity
Last Updated :
18 Sep, 2024
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.
- Precision: Avoids the inaccuracies associated with floating-point numbers.
- Performance: Integer operations are faster and cheaper in terms of gas usage.
- 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:
- Addition: Adds two fixed-point numbers by simply summing them up.
- Subtraction: Subtracts one fixed-point number from another while ensuring no underflow occurs.
- Multiplication: Multiplies two fixed-point numbers, then scales the result down to maintain the correct precision.
- 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:
Deploying ContractInput Fields:
Empty Input Fields
Example Input FieldsOutput:
OutputAddition 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:
Deployed ContractInput Fields:
Empty Input Fields
Example Input FieldsOutput:
OutputMultiplication 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:
Deployed ContractInput Field:
Empty Input Fields
Example Input FieldsOutput:
OutputStep-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
- In the left sidebar, you'll see a file explorer. Click on the + icon to create a new file.
- 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);
}
}
FixedPointArithmatic.sol Contract Code4. Compile the Contract
- Select the Solidity Compiler tab on the left sidebar (it looks like a "compiler" icon).
- Ensure the compiler version is set to 0.8.0 or higher (since your contract uses pragma ^0.8.0).
- Click the Compile FixedPointArithmetic.sol button. You should see a green checkmark if the compilation is successful.
5. Deploy the Contract
- Go to the Deploy & Run Transactions tab (it looks like an "Ethereum" icon).
- Select Remix VM (Cancun) from the Environment dropdown. This setting runs a local blockchain in your browser.
- Ensure that the FixedPointArithmetic contract is selected in the Contract dropdown.
- 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:
Deployed FixedPointArithmeticStruct.sol ContractInput Fields:
Empty Input Fields
Example Input FieldsOutput of All Example Inputs:
OutputsAll Transaction Log - Deployed Contract and Deployed Functions:
All Transactions Log1. 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.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Python Variables In Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Spring Boot Interview Questions and Answers Spring Boot is a Java-based framework used to develop stand-alone, production-ready applications with minimal configuration. Introduced by Pivotal in 2014, it simplifies the development of Spring applications by offering embedded servers, auto-configuration, and fast startup. Many top companies, inc
15+ min read