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
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.
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
The easiest way is to use arg of QString.
QString str = QString("%L1").arg(yourDouble);
for qml users:
function thousandSeparator(input){
return input.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With