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
Solidity - Integers Integers help store numbers in smart contracts. Solidity provides two types of integers: Signed Integers: Signed integers can hold both positive and negative values, ranging from -2 ^ 255 to 2 ^255 - 1.Unsigned Integers: Unsigned integers can hold only integer values equal to or greater than zero, r
5 min read
Are all whole numbers positive? The method to represent and work with numbers is known as the number system. A number system is a system of writing to represent numbers. It is the mathematical notation used to represent numbers of a given set by using digits or other symbols. It allows us to operate arithmetic operations such as d
5 min read
Playing with Numbers Playing with Numbers: Numbers are the mathematical objects used to count, measure, and label. The original examples are the natural numbers 1, 2, 3, 4, and so forth. Numbers can be represented in language with number words. More universally, individual numbers can be represented by symbols, called n
11 min read
Perl | Number and its Types A Number in Perl is a mathematical object used to count, measure, and perform various mathematical operations. A notational symbol that represents a number is termed as a numeral. These numerals, in addition to their use in mathematical operations, are also used for ordering(in the form of serial nu
4 min read
What is a Whole Number? Numbers are the mathematical figures or values applicable for counting, measuring, and other arithmetic calculations. Some examples of numbers are integers, whole numbers, natural numbers, rational and irrational numbers, etc.In this article, we will answer the question "What are whole numbers?" alo
5 min read
Are fractions whole numbers? Numerals are the mathematical figures used in financial, professional as well as a social field in the social world. The digits and place value in the number and the base of the number system determine the value of a number. Numbers are used in various mathematical operations as summation, subtracti
5 min read