Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ String to double atof conversion losing precision?

Tags:

c++

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

like image 511
sapatos Avatar asked Jan 24 '11 04:01

sapatos


2 Answers

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.

like image 72
Raph Levien Avatar answered Sep 27 '22 18:09

Raph Levien


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);
like image 37
sth Avatar answered Sep 27 '22 17:09

sth