Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert uint to string in solidity?

In Solidity, is there a way I can convert my int to string ?

Example:

pragma solidity ^0.4.4;

contract someContract {

    uint i;

    function test() pure returns (string) {

      return "Here and Now is Happiness!";

    }

    function love() pure returns(string) {

        i = i +1;

        return "I love " + functionname(i) + " persons" ;
    }



}

What is functionname?Thanks!

like image 680
Bob Zheng Avatar asked Nov 06 '17 03:11

Bob Zheng


Video Answer


2 Answers

solidity ^0.8.0

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

Strings.toString(myUINT)

works for me.

https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol#L15-L35

like image 130
JR White Avatar answered Oct 21 '22 13:10

JR White


UPDATE for Solidity 0.8.0:

The uint2str() function from https://github.com/provable-things/ethereum-api/blob/master/provableAPI_0.6.sol is now outdated, and will not work, but here is the updated code, that uses solidity 0.8.0: (there was an Overflow bug in the last version but solidity <0.8.0 ignored that as it did not affect the answer, but that now throws an error) byte was also changed to bytes1 and +,-,* and so on work like they would from the SafeMath library.

function uint2str(uint _i) internal pure returns (string memory _uintAsString) {
        if (_i == 0) {
            return "0";
        }
        uint j = _i;
        uint len;
        while (j != 0) {
            len++;
            j /= 10;
        }
        bytes memory bstr = new bytes(len);
        uint k = len;
        while (_i != 0) {
            k = k-1;
            uint8 temp = (48 + uint8(_i - _i / 10 * 10));
            bytes1 b1 = bytes1(temp);
            bstr[k] = b1;
            _i /= 10;
        }
        return string(bstr);
    }
like image 36
Barnabas Ujvari Avatar answered Oct 21 '22 13:10

Barnabas Ujvari