C++ 将货币格式字符串转换为双精度

C++ 将货币格式字符串转换为双精度,c++,formatting,C++,Formatting,将货币格式字符串转换为双精度字符串的最简单方法是什么 例如,1234567.00至1234567.00 到目前为止,字符串替换与stringstream结合使用是我最好的选择 我还没有上C++11。因此,不是一个选项您可以在删除所有“,”字符后,使用C函数atof: #include <string> #include <algorithm> #include <stdlib.h> double strToDouble(string str) { s

将货币格式字符串转换为双精度字符串的最简单方法是什么

例如,1234567.00至1234567.00

到目前为止,字符串替换与stringstream结合使用是我最好的选择


我还没有上C++11。因此,不是一个选项

您可以在删除所有“,”字符后,使用C函数atof:

#include <string>
#include <algorithm>
#include <stdlib.h>

double strToDouble(string str)
{
    str.erase(remove(str.begin(), str.end(), ','), str.end());
    return atof(str.c_str());
}
#包括
#包括
#包括
双字符串strToDouble(字符串str)
{
str.erase(删除(str.begin()、str.end()、'、'、str.end());
返回atof(str.c_str());
}

它也可以在不使用任何C++11功能的情况下工作。

请查看此项。虽然它很大,但它能满足你的目的-

    string str = "1,234,567.00",temp="";
    temp.resize(str.size());

    double first = 0.0, sec = 0.0;

    int i=0;
    int tempIndex = 0;

    while(i<str.size() && str[i]!='.')
    {
        if(str[i]!=',')
          temp[tempIndex++]=str[i];
        i++;
    }

    if(temp.size()>0)
    {
        for(int index = 0; index < tempIndex ; index++)
        {
            first = first*10.0 + (temp[index]-'0');
        }
    }

    if(i<str.size())
    {
        double k = 1;
        i++; // get next number after decimal
        while(i<str.size())
        {
            if(str[i]==',')
            {
              i++;
              continue;
            }
            sec += (str[i]-'0')/(pow(10.0,k));
            i++;
            k++;
        }
    }

    double num = first+sec;
    if(str[0]=='-')
    num = (-1.0*num);
    printf("%lf\n",num);
string str=“1234567.00”,temp=“”;
临时调整大小(str.size());
双首=0.0,秒=0.0;
int i=0;
int tempIndex=0;
while(i0)
{
对于(int index=0;index如果(iC++11的
std::get_money
只调用C++98