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.开发者_如何学JAVA
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,");
}
Since you don't want QLocale perhaps you could do a simple conversion (with QString::number, for example) and then replace the desired characters afterwards.
pretty horrible, but got the job done
double doubleNumber = 5234556.3545;
int precision = 2;
QString stringNumber = QString::number(doubleNumber, 'f', precision);
for(int point = 0, i = (stringNumber.lastIndexOf('.') == -1 ? stringNumber.length() : stringNumber.lastIndexOf('.')); i > 0; --i, ++point)
{
if(point != 0 && point % 3 == 0)
{
stringNumber.insert(i, ',');
}
}
精彩评论