Convert string with thousands (and decimal) separator into double

前端 未结 2 1265
梦如初夏
梦如初夏 2021-01-06 02:22

User can enter double into textbox. Number might contain thousands separators. I want to validate user input, before inserting entered number into database.

相关标签:
2条回答
  • 2021-01-06 02:32

    A C solution would be to use setlocale & sscanf:

    const char *oldL = setlocale(LC_NUMERIC, "de_DE.UTF-8");
    double d1 = 1000.43, d2 = 0;
    sscanf("1.000,43", "%'lf", &d2);
    if ( std::abs(d1-d2) < 0.01 )
      printf("OK \n");
    else
      printf("something is wrong! \n");
    setlocale(LC_NUMERIC, oldL);
    
    0 讨论(0)
  • 2021-01-06 02:42

    Convert the input to double using a stream that's been imbued with a locale that accepts thousand separators.

    #include <locale>
    #include <iostream>
    
    int main() {
        double d;
    
        std::cin.imbue(std::locale(""));
        std::cin >> d;
    
        std::cout << d;
    }
    

    Here I've used the un-named locale, which retrieves locale information from the environment (e.g., from the OS) and sets an appropriate locale (e.g., in my case it's set to something like en_US, which supports commas as thousands separators, so:

    Input: 1,234.5
    Output: 1234.5
    

    Of course, I could also imbue std::cout with some locale that (for example) uses a different thousands separator, and get output tailored for that locale (but in this case I've used the default "C" locale, which doesn't use thousands separators, just to make the numeric nature of the value obvious).

    When you need to do this with something that's already "in" your program as a string, you can use an std::stringstream to do the conversion:

    std::string input = "1,234,567.89";
    
    std::istringstream buffer(input);
    buffer.imbue(std::locale(""));
    
    double d;
    buffer >> d;
    
    0 讨论(0)
提交回复
热议问题