2

I've found how to convert an unsigned int256 in oraclizeAPI.sol and Ethereum String Utils but I haven't had any luck finding how to convert a signed int256 into a string.

    function uint2str(uint i) internal pure returns (string){
    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 - 1;
    while (i != 0){
        bstr[k--] = byte(48 + i % 10);
        i /= 10;
    }
    return string(bstr);
}
heyyouyayou
  • 33
  • 1
  • 3

2 Answers2

2

It is a good exercise to modify uint2str to handle signed input.

function int2str(int i) internal pure returns (string){
    if (i == 0) return "0";
    bool negative = i < 0;
    uint j = uint(negative ? -i : i);
    uint l = j;     // Keep an unsigned copy
    uint len;
    while (j != 0){
        len++;
        j /= 10;
    }
    if (negative) ++len;  // Make room for '-' sign
    bytes memory bstr = new bytes(len);
    uint k = len - 1;
    while (l != 0){
        bstr[k--] = byte(48 + l % 10);
        l /= 10;
    }
    if (negative) {    // Prepend '-'
        bstr[0] = '-';
    }
    return string(bstr);
}
Ismael
  • 30,570
  • 21
  • 53
  • 96
  • This version is not efficient at all, probably should use the one from https://github.com/pipermerriam/ethereum-string-utils as base. – Ismael Dec 07 '17 at 03:10
0

Solidity is indifferent to character sets regarding strings there is no toString function in solidity

This question has also been answered before: Conversion of uint to string

jold20
  • 156
  • 7