Click to See Complete Forum and Search --> : problem about converting from string to long double
ALEXSNIPER
July 15th, 2008, 04:20 PM
hi
i hope to get your help about this problem
i want to write Function that convert from string
as "$123,456,789,157.65"
to long double to use it in mathematical operations
laasunde
July 15th, 2008, 04:27 PM
This should get you started http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2
Lindley
July 15th, 2008, 04:47 PM
Well, first you'd have to remove the commas. Then a simple sscanf() should do the trick with the %lg format specifier. Or you could try strtod() or atof()....just be careful about the dollar sign, whatever you do.
ALEXSNIPER
July 15th, 2008, 05:08 PM
notice that its long double not double
this mean the number my be 19 digit so i can't use atof() or atod()
i oop with c++ book he saied i can use _atold() in math.h but no function like this in math.h
but first i must delete commas
i can do it by storing it in new char* and convert each number like this
long to double stold(char* str)
{
long double number=0.0;
char* s;
int n=0;
while(str[n]!=NULL)
{
if(str[n]>='0'||str[n]<='9'||str[n]=='.')
s[n]=str[n];
}//end while
for(int i=0;i<strlen(s);i++)
{
number+=static_cast<int>(s[n]-'0')*pow(10.0,i);
}
return number;
}
i don't know if this work or no
i want to know your openion
thnx for your help
Lindley
July 15th, 2008, 09:22 PM
If you're only expecting two decimal places (common with money), then you can easily read a 64-bit int (long long int) on the left of the decimal, and a standard int on the right. These use the %lld specifier. It's then trivial to add the left hand side to the right hand side over 100.0, and store the result in a long double.
Of course, you may wish to ensure the right hand side is really only two digits before you do the conversion.
In my opinion, though, once you start needing more than double precision, you're probably best off getting yourself an infinite precision library and using that.
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.