[solved] QLocale - with atof - why doesn't it convert "3.3"?



  • Hi, I've been having a problem for quite some while now with the Qt locale.
    I'm using Qt 4.6.2 on Ubuntu 10.04 64. In my code I'm using a library that uses the function
    atof (from stdlib.h), normally this would return for example:
    atof("4.4") = 4.4; but in my case it works only with atof("4,4")=4.4
    Since my System is set to ES locale, I understand that it uses commas, but when I try to set the locale to US-EN, it still doesn't work:

    @
    #include <QtCore/QCoreApplication>
    #include <QLocale>

    #include <iostream>
    #include <cmath>
    #include <cstdlib>

    using namespace std;

    int main(int argc, char *argv[])
    {
    QCoreApplication a(argc, argv);

    QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));

    cout << "arg[1]   : " << argv[1] << endl;
    cout << "atof(arg): " << atof(argv[1])<<endl;
    

    return 0;
    }
    @

    This gives:
    @$ ./mtest 3.3
    arg[1] : 3.3
    atof(arg): 3

    $ ./mtest 3,3
    arg[1] : 3,3
    atof(arg): 3.3
    @

    Anyone knows how I can change the locale such that I don't have to change the library's code?

    Thanks in advance!



  • atof doesn't care about [[Doc:QLocale]] settings and QLocale doesn't change the posix locale of the process. You need to set the environment variable LANG (or LC_NUMERIC).



  • Thanks! It worked using setlocale(..)!

    @
    #include <QtCore/QCoreApplication>
    //#include <QLocale>
    #include <locale.h>

    #include <iostream>
    #include <cmath>
    #include <cstdlib>

    using namespace std;

    int main(int argc, char *argv[])
    {
    QCoreApplication a(argc, argv);

    // QLocale::setDefault(QLocale(QLocale::English, QLocale::UnitedStates));
    setlocale(LC_NUMERIC,"en_US");

    cout << "arg[1] : " << argv[1] << endl;
    cout << "atof(arg): " << atof(argv[1])<<endl;
    return 0;
    }
    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.