将货币格式字符串转换为double

时间:2014-07-21 22:09:53

标签: c++ formatting

将货币格式化字符串转换为双打

的最简单方法是什么?

例如,1,234,567.00至1234567.00

到目前为止,

字符串替换与stringstream一起是我最好的选择。

我还没有使用C ++ 11。因此,http://en.cppreference.com/w/cpp/io/manip/get_money不是一个选项

2 个答案:

答案 0 :(得分:1)

删除所有“,”字符后,您可以使用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());
}

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

答案 1 :(得分:0)

请检查一下。虽然它很大,但它会满足你的目的 -

    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);

我会使用它而不是使用STL。