Qt - custom decimal point and thousand separator

后端 未结 6 1850
野趣味
野趣味 2021-02-13 23:52

How can I convert a number (double) to string, with custom decimal point and thousand separator chars?

I\'ve seen QLocale, but I don\'t want to choose the localization c

6条回答
  •  遇见更好的自我
    2021-02-14 00:24

    Here is how you do it just using the std::lib (no QT). Define your own numpunct-derived class which can specify decimal point, grouping character, and even the spacing between groupings. Imbue an ostringstream with a locale containing your facet. Set the flags on that ostringstream as desired. Output to it and get the string from it.

    #include 
    #include 
    #include 
    
    class my_punct
        : public std::numpunct
    {
    protected:
        virtual char do_decimal_point() const {return ',';}
        virtual char do_thousands_sep() const {return '.';}
        virtual std::string do_grouping() const  {return std::string("\2\3");}
    };
    
    int main()
    {
        std::ostringstream os;
        os.imbue(std::locale(os.getloc(), new my_punct));
        os.precision(2);
        fixed(os);
        double x = 123456789.12;
        os << x;
        std::string s = os.str();
        std::cout << s << '\n';
    }
    

    1.234.567.89,12

提交回复
热议问题