C++字符串、浮点数转换小demo

#include <iostream>
#include <iomanip>
#include <string>

template<typename T>
T string_to_number(const std::string &numberAsString) {
    using namespace std;
    T valor;

    stringstream stream(numberAsString);
    stream >> valor;
    if (stream.fail()) {
        throw runtime_error("string_to_number(): " + numberAsString);
    }
    return valor;
}

template<typename T>
std::string num_to_string_with_precision(const T a_value, const int n = 6) {
    using namespace std;
    std::ostringstream out;
    std::fixed(out);
    out << std::setprecision(n) << a_value;
    return out.str();
}

int main() {
    using namespace std;

    try {
        std::string str_num = "1997.1009f";
        double d = string_to_number<double>(str_num);
        cout << std::fixed << std::setprecision(4);
        cout << d << endl;

//        double d2 = stod(str_num);
//        cout.width(3);
//        cout.setf(ios::fixed);
//        cout.precision(4);
//        cout << d2 << endl;

        string s = num_to_string_with_precision(d, 4);
        cout << s << endl;
    } catch (exception &e) {
        std::cerr << "Error occurred, " << e.what() << std::endl;
    }

    return 0;
}

  运行结果:

 

posted on 2019-09-25 11:51  areful  阅读(257)  评论(0编辑  收藏  举报

导航