代码之家  ›  专栏  ›  技术社区  ›  Kelly Beard

ios_base::修复了截断尾随零(&T)

  •  0
  • Kelly Beard  · 技术社区  · 6 年前

    当打印某些十进制数时,可能会发生舍入(我目前的平台是ibmiseries)。如果我设置ios_base::fixed,效果会更好,但会打印讨厌的尾随(和无关紧要的)零。有没有更好的办法?对于我使用的平台,输出如下:

    myval=100000
    myval=99999.990000
    myval as string =99999.990000
    
    #include <iostream>
    #include <string>
    #include <sstream>
    #include <iomanip>
    #include <unistd.h>
    #include <algorithm>
    
    using namespace std;
    
    // returns t
    template<typename T> string toString(const T& val)
    {
        stringstream os;
    
        os.setf(std::ios_base::fixed);
        os << val;
        return os.str();
    }
    
    class MyApp {
    private :
    public :
        MyApp();
        virtual ~MyApp();
    
        void run();
    
        operator bool() const { return true; }
    };
    
    
    MyApp::MyApp()
    {
    }
    
    MyApp::~MyApp()
    {
    }
    
    void MyApp::run()
    {
        double myval = 99999.99;
        string myval_as_string = toString<double>(myval);
    
        cout << "myval=" << myval << endl;
    
        cout.setf(std::ios_base::fixed);
    
        cout << "myval=" << myval << endl;
        cout << "myval as string =" << myval_as_string << endl;
    }
    
    int main(int argc, char* argv[])
    {
        MyApp myApp;
    
        myApp.run();
    }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Player1st    6 年前

    你在找 precision 而不是 fixed 精度 将指定所使用的最大精度,但不会自动打印更多的零,因此可以根据需要增加它。 会迫使它变成0 设置为。如果你已经准备好了 固定的 以前,您可以使用 ios_base::defaultfloat

    template<typename T> string toString(const T& val)
    {
        stringstream os;
    
        os.precision(15);
        os << val;
        return os.str();
    }
    ....
    void MyApp::run()
    {
        double myval = 99999.99;
        string myval_as_string = toString<double>(myval);
    
        cout << "myval=" << myval << endl;
        cout.precision(15);
        cout << "myval=" << myval << endl;
        cout << "myval as string =" << myval_as_string << endl;
    }
    

    欲了解更多信息,请访问以下标准: http://www.cplusplus.com/reference/ios/ios_base/precision/

    使用默认的浮点表示法,精度字段 指定要总共显示的有意义数字的最大数目 同时计算小数点前后的数字。通知 它不是最小值,因此它不会填充显示的内容 如果数字可以用较小的