const char* 与 C++ 双重翻译问题

const char* to double translation issue with C++

我有两个使用同一个库的示例应用程序,它们之间的主要区别在于一个使用 qt 而另一个应用程序是控制台应用程序。

在公共库中,我有这个测试代码:

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

如果我使用非 qt 应用程序,则值为:

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

但使用 qt 应用程序:

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

是否存在 'atof' 的行为因为 qt 而改变的情况?

您注意到的问题很可能是由 Qt 的语言环境概念引起的。您可以使用:

QLocale::setDefault(QLocale::C);

让它像 atof 一样工作。

更新

似乎QLocale::setDefault 没有设置Qt 使用的默认语言环境。它仅设置在您构造 QLocale 时将创建的默认语言环境。有关详细信息,请参阅 Changing locale in Qt 和已接受的答案。

std::atof 取决于当前设置的语言环境来告诉它哪个字符是小数点。在默认情况下 ("C locale"),即句点字符 '.'。

Qt 可能将区域设置设置为其他内容。您可以使用 standard C[++] mechanism:

恢复它
std::setlocale(LC_ALL, "C");