Large numeric literals should use underscores for readability
Learn why using underscores for large numeric literals in your Solidity code can enhance readability and make values clearer. Discover how this simple technique can help you better understand the magnitude of numbers at a glance.
Category
non-critical
Languages
solidity
Analysis Layer
static
Severity
info
At a glance, it's quite difficult to understand how big this number is. Use underscores to make values more clear.
When dealing with large numeric literals in Solidity, it can be challenging to determine the magnitude of the value at first sight. As a developer, it is crucial to write clean and readable code that allows others (including yourself) to easily interpret these values.
Thankfully, Solidity provides a simple yet effective solution to enhance the readability of large numeric literals: using underscores. By incorporating underscores in the numeric literals, the value becomes much clearer and easier to understand.
Consider the following example:
pragma solidity ^0.8.0;
contract LargeNumberExample {
uint256 public largeNumber = 1000000000000000000000000;
}
Without any additional formatting, it is not apparent how big the largeNumber truly is. By adding underscores to the numeric literal, we can make it more readable:
pragma solidity ^0.8.0;
contract LargeNumberExample {
uint256 public largeNumber = 1_000_000_000_000_000_000_000_000;
}
Now, it is evident that largeNumber has 24 digits, representing a one followed by twenty-three zeros.
Using underscores as separators does not affect the compiled bytecode or the execution of the contract in any way; it is purely an aid for human readability. The Solidity compiler automatically removes the underscores during compilation, ensuring that the correct numerical value is utilized.
Remember, using underscores for improved readability is not limited to large numeric literals. It can also be beneficial when dealing with long hexadecimal values or any value that involves numerous digits.
In summary, by incorporating underscores in large numeric literals or any lengthy numeric representation, you can make your code more readable and understandable. This practice promotes code maintainability and reduces the risk of misunderstanding or misinterpreting the value.
Happy coding!
RELATED ARTICLE: Preventing Integer Overflow and Underflow in Solidity