2013-08-25 101 views
1

在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

但如何扭转这种不明确的,我想知道如何做到这一点的操作非常有用?

+0

在*双*存储这些类型的数字几乎是从来不是一个错误。货币值应该存储在使用base-10编码的数据类型中,如C#的System.Decimal。在C++标准中不支持,你需要去购物。否则,在使用COleCurrency类的MSVC++中支持,请注意ParseCurrency()方法。 –

+0

感谢您的评论,但这真的没有帮助我用它来解析234,098.6700,它把它当作234.0000,它不能理解数字分组符号。我发现这篇文章也http://www.codeproject.com/Articles/9600/Windows-SetThreadLocale-and-CRT-setlocale直到现在我没有读到它,如果我发现任何解决方案,我会在这里提到它 – ahmedsafan86

回答

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. 
+0

这很好,我看过它,但我的问题是如何获得当前线程的区域设置名称?这是一个很大的挑战,我的目标客户端PC,我不知道它是什么语言环境设置英语或德语或阿拉伯语,..... – ahmedsafan86

+0

@Ahmed safan:意味着上述代码不起作用的线程!? –

+0

它的工作原理,但你写'你可能不得不调整'en_GB.utf8'',我希望它与线程语言环境相同,此方法获取当前线程语言环境作为ID但不是名称http:// msdn.microsoft.com/en-us/library/windows/desktop/dd318127(v=vs.85).aspx – ahmedsafan86

相关问题