Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt - custom decimal point and thousand separator

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 country, but rather specify my own decimal point and thousand separator chars.

Thanks

like image 972
Stari As Avatar asked Feb 17 '11 22:02

Stari As


4 Answers

Qt doesn't support custom locale. But to deal with just group and decimal point characters is trivial:

const QLocale & cLocale = QLocale::c();
QString ss = cLocale.toString(yourDoubleNumber, 'f');
ss.replace(cLocale.groupSeparator(), yourGroupChar);
ss.replace(cLocale.decimalPoint(), yourDecimalPointChar);

BTW, spbots' question is not irrelevant. More detail about the goal always helps and it could lead to different approach that may serve you better.

like image 73
Stephen Chu Avatar answered Nov 14 '22 05:11

Stephen Chu


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 <locale>
#include <sstream>
#include <iostream>

class my_punct
    : public std::numpunct<char>
{
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

like image 26
Howard Hinnant Avatar answered Nov 14 '22 05:11

Howard Hinnant


The easiest way is to use arg of QString.

QString str = QString("%L1").arg(yourDouble);
like image 4
Ahad aghapour Avatar answered Nov 14 '22 06:11

Ahad aghapour


for qml users:

function thousandSeparator(input){
    return input.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}
like image 2
Hamed Nikzad Avatar answered Nov 14 '22 05:11

Hamed Nikzad