将数字转换为格式化字符串并再次解析格式化字符串

时间:2013-08-25 10:25:54

标签: c++ winapi localization globalization

在visual c ++中,我需要使用窗口的数字格式根据当前线程区域设置格式化数字,例如使用数字分组分隔符和窗口小数点,也可以像C#.NET一样再次解析它。

convert double b = 108457000.89 to "108,457,000.89"
also convert "108,457,000.89" to double b = 108457000.89

这篇文章在将数字转换为格式化字符串http://www.codeproject.com/Articles/14952/A-simple-class-for-converting-numbers-into-a-strin

时非常有用

但是如何扭转不明确的操作我想知道怎么做?

1 个答案:

答案 0 :(得分:2)

您可以这样做(并忽略该文章):

#include <iomanip>
#include <iostream>
#include <sstream>

int main() {

    // Environment
    std::cout << "Global Locale: " << std::locale().name() << std::endl;
    std::cout << "System Locale: " << std::locale("").name() << std::endl;

    // Set the global locale (To ensure it is English in this example,
    // it is not "")
    std::locale::global(std::locale("en_GB.utf8"));
    std::cout << "Global Locale: " << std::locale().name() << std::endl;

    // Conversion string to double
    std::istringstream s("108,457,000.89");
    double d = 0;
    s >> d;
    // Conversion double to string
    std::cout << std::fixed << d << std::endl;
    // This stream (initialized before main) has the "C" locale,
    // set it to the current global:
    std::locale c = std::cout.imbue(std::locale());
    std::cout << "Locale changed from " << c.name()
        << " to " << std::cout.getloc().name() << std::endl;
    std::cout << std::fixed << d << std::endl;

    return 0;
}

注意:

  • 在终端/控制台中运行它(我的开发环境Eclipse有 C语言环境)
  • 您可能需要调整“en_GB.utf8”

结果:

Global Locale: C
System Locale: en_US.UTF-8
Global Locale: en_GB.utf8
108457000.890000
Locale changed from C to en_GB.utf8
108,457,000.890000

警告:

Libraries may rely on the global local being the "C" local.