[Ethereum] How convert signed int256 into a string

solidity

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);
}

Best Answer

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);
}