Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

const char* to double translation issue with C++

Tags:

c++

qt

atof

I have two sample applications using the same library and the main difference between them is that one uses qt and the other application is a console application.

In the common library, I have this test code:

double test = 0.1;
double test2 = atof("2.13134");
double test3 = atof("1,12345");

The values if I use the non-qt application are:

test = 0.10000000000001
test2 = 2.1323399999999999998
test3 = 1   // This is the expected result using a ',' as delimitation character

But with the qt application:

test = 0.10000000000001
test2 = 2     // This is not expected!!!
test3 = 1.1234500000000000001

Is there any case where the behaviour of the 'atof' changes because qt?

like image 989
goe Avatar asked Feb 09 '16 14:02

goe


2 Answers

std::atof depends on the currently set locale to tell it which character is the decimal point. In the default case ("C locale"), that is the period character '.'.

It's likely that Qt is setting the locale to something else. You can revert that using the standard C[++] mechanism:

std::setlocale(LC_ALL, "C");
like image 87
Angew is no longer proud of SO Avatar answered Nov 03 '22 00:11

Angew is no longer proud of SO


The problem you are noticing is most likely caused by Qt's notion of locale. You can use:

QLocale::setDefault(QLocale::C);

to make it work like atof.

Update

It seems QLocale::setDefault does not set the default locale used by Qt. It merely sets the default locale that will be created when you construct a QLocale. See Changing locale in Qt and the accepted answer for more info.

like image 25
R Sahu Avatar answered Nov 02 '22 23:11

R Sahu