C++ is not my language so forgive this simple problem. I'm losing precision in an atof conversion from string to double, can anyone help?
string lAmount;
string lSuspendedInt = "131663.51";
string lAccruedInterest = "0.0";
double dSuspendedInt= atof(lSuspendedInt.c_str()); //PROBLEM HERE?
double dAccruedInterest = atof(lAccruedInterest.c_str());
double dTotal = dSuspendedInt + dAccruedInterest;
char cAmount[50];
memset(cAmount,0X00,sizeof(cAmount));
sprintf(cAmount,"%g*",dTotal);
lAmount = cAmount;
cout << "lAmount: "<<lAmount<<endl; //PRINTING: 131664 not 131663.51
I've played with %f in the memset function however this gives 131663.510000
Thanks in advance.
Sapatos
The problem is your %g
format operator, which isn't specified with enough precision. You might want %.2f
instead, which prints two digits after the decimal point.
The sprintf
%g
format specifier defaults to printing six significant digits. If you want more, you can explicitly specify how many should be printed:
sprintf(cAmount,"%.8g*",dTotal);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With