float转string

23 阅读1分钟
std::string i2s(int i, int times)
{
    if (i == 0)
    {
        return "0";
    }
    std::vector<int> v;
    v.reserve(16);
    while (i > 0)
    {
        v.push_back(i % 10);
        i /= 10;
        --times;
    }
    std::stringstream ss;
    for (int j = v.size() - 1; j >= 0; --j)
    {
        --times;
        ss << v[j];
    }
    return ss.str();
}
std::string float2str(float f)
{
    std::stringstream result;
    if (f < 0)
    {
        result << "-";
        f = -f;
    }
    int z = int(f);
    float x = f - float(z);

    result << i2s(z, 0);
    if (x < 1e-6)
    {
        return result.str();
    }
    int times = 0;
    while (x - int(x) > 1e-6)
    {
        x *= 10;
        ++times;
    }
    result << "." << i2s(int(x), times);
    return result.str();
}

int main()
{
    cout << float2str(2.5) << endl;
    cout << float2str(10.5) << endl;
    cout << float2str(0.55002564565555) << endl;
    return 0;
}