Monday, January 8, 2024

Quick Bytes: Solidity Function To Convert Uint256 To String

 Here's a quick piece of code for a Solidity function to do the conversion:

  // Converts a uint256 variable to a string
  function uint2str(uint256 _i) private pure returns(string memory) {

      if (_i == 0) {
          return "0";
      }
      
      uint256 j = _i;
      uint256 length;

      while (j != 0) {
          length++;
          j /= 10;
      }
 
      bytes memory bstr = new bytes(length);
      uint256 k = length;

      while (_i != 0) {
          k = k - 1;
          uint8 temp = (48 + uint8(_i % 10));
          _i /= 10;
          bstr[k] = bytes1(temp);
      }

      return string(bstr);

  }