2013-08-25 100 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

相關問題