theAlias
theAlias

Reputation: 396

Converting money format string to double

What is the simplest way to convert a money formatted string to doubles

eg., 1,234,567.00 to 1234567.00

string replace in conjunction with stringstream is my best option so far.

I'm not on C++11 yet. So, http://en.cppreference.com/w/cpp/io/manip/get_money is not an option

Upvotes: 0

Views: 2231

Answers (2)

Naseef Chowdhury
Naseef Chowdhury

Reputation: 2464

Please check this out. Though it is large, but it will serve your purpose -

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

I would have used this instead of using STL.

Upvotes: 0

BlackDwarf
BlackDwarf

Reputation: 2070

You can use the C function atof, after removing all the "," characters:

#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());
}

It also works without using any C++11 feature.

Upvotes: 1

Related Questions