How to convert asset to string in a contract?
asset my_asset = asset(10000, S(4, EOS));
string my_asset_string = ??? //How to convert my_asset to a string "1.0000 EOS"?
Actually asset is a struct variable like this:
struct asset {
/**
* The amount of the asset
*
* @brief The amount of the asset
*/
int64_t amount;
/**
* The symbol name of the asset
*
* @brief The symbol name of the asset
*/
symbol_type symbol;
...
...
}
we can find the convert from asset to string in the file ./libraries/chain/asset.cpp line 23 like this
string asset::to_string()const {
string sign = amount < 0 ? "-" : "";
int64_t abs_amount = std::abs(amount);
string result = fc::to_string( static_cast<int64_t>(abs_amount) / precision());
if( decimals() )
{
auto fract = static_cast<int64_t>(abs_amount) % precision();
result += "." + fc::to_string(precision() + fract).erase(0,1);
}
return sign + result + " " + symbol_name();
}
+ symbol_name()
? That is how you get the symbol
Commented
Aug 14, 2018 at 11:29
You cannot use functions from ./libraries/chain/asset.cpp directly in your contract. The only available part of EOS API you can use in contacts is located in ./contracts/eosiolib/ folder. There are files, which define "asset" and "symbol" structure, but there are no functions, that convert values to string. So, you need to use your implementation inside the contracts.
Here is my implementation I'm using for my smart contracts:
std::string asset_to_string(asset val) const
{
string sign = val.amount < 0 ? "-" : "";
uint64_t abs_amount = static_cast<uint64_t>(std::abs(val.amount));
auto precision = val.symbol.precision();
string result = std::to_string( abs_amount);
if( precision > 0 )
{
auto p = precision;
uint64_t p10 = 1;
while(p > 0) {
p10 *= 10;
p--;
}
result = std::to_string( static_cast<uint64_t>(abs_amount / p10));
auto fract = abs_amount % p10;
result += "." + std::to_string(p10 + fract).erase(0,1);
}
return sign + result + " " + symbol_to_string(val);
}
std::string symbol_to_string(asset val) const
{
uint64_t v = val.symbol.value;
v >>= 8;
string result;
while (v > 0) {
char c = static_cast<char>(v & 0xFF);
result += c;
v >>= 8;
}
return result;
}
I've just extracted the code from ./libraries/chain and used it with "asset" and "symbol" from eosiolib.
Usage:
std::string assetString = asset_to_string(assetVar);
asset my_asset = asset(10000, S(4, EOS));
std::string myString = my_asset.to_string();