I'm writing a program that inputs the amount of money and outputs it preceded by dollar sign and divided by commas into groups of three digits
I'll enter the money as string and call function called mstold()and returns an equivalent number as long double so my problem is how can I get the a number long double equivalent to string and this is my code :

``````long double mstold(string money)
{
long double amnt;
for(int i=0;i<money.length();i++)
{
amnt=money[i]*10+1;
}
return amnt;
}
int _tmain(int argc, _TCHAR* argv[])
{
string money;
cout<<"Enter the amount of money you want to convert to long double";         cin>>money;
cout<<"\n\namount in long double :  "<<mstold(money)<<endl;
return 0;}``````

Thank you :)

## All 4 Replies

If you want to convert it yourself then amnt=money*10+1; is incorrect. Should be something like below -- you can not assume the string contains all numeric digits.

``````while( isdigit(money[i]) )
{
amnt = (amt*10) + money[i] - '0';
++i;
}``````

Now do something similar for the cents. You might have to use another variable for this, then put the two together.

thanks l7sqr and ancient dragon for you help but I want to ask something for
l7sqr : the strtold is not built in I've tried to find it but I didn't so if you could tell me the reason why I didn't find it ? Thank you :)

for ancient dragon: if I entered number like this "123,456,789.12"it will output only 123 I don't like to look lazy but I really don't know how to make the number be outputed with the commas and not adding the commas the output in long double will be 123,456,789.12 with the decimal point Thank you :)

There are no standard C functions that will convert a string that contains commas as you posted. You will have to write your own custom function to do that. Same with outputting.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.