How To Convert Uint To String In Solidity?

To convert a uint (unsigned integer) to a string in Solidity, you can use the following method since Solidity does not have a built-in function for direct conversion.

  1. Import Required Libraries:
    You can use the Strings library found in OpenZeppelin to convert numbers to strings.
  2. Create a Function for Conversion:
    We will create a function that uses the Strings library’s toString() method to convert a uint to a string.

Table of Contents

Example Code

pragma solidity ^0.8.0;

import "@openzeppelin/contracts/utils/Strings.sol";

contract UintToString {
    using Strings for uint256;

    function uintToString(uint256 value) public pure returns (string memory) {
        return value.toString();
    }
}

Code Explanation

  1. Pragma Directive:
    • At the top, we specify the version of Solidity we’re using (pragma solidity ^0.8.0;). This ensures compatibility with the code.
  2. Import Statement:
    • We import the Strings library from OpenZeppelin. This library provides utility functions, including toString() for converting uint to string.
  3. Contract Declaration:
  • We define a contract named UintToString.
  1. Using the Library:
    • We use using Strings for uint256; which allows us to call the toString() function directly on uint256 types.
  2. Function Creation:
    • The uintToString function takes a uint256 parameter (value) and returns a string memory.
    • Inside the function, we call value.toString() to perform the conversion and return the result.

Usage

To use the uintToString function, you would deploy the UintToString contract and call the function with a uint value, like this:

uint256 myNumber = 12345;
string memory stringValue = contract.uintToString(myNumber);

In this way, you can effectively convert a uint to a string in Solidity using the Strings library.