sapatos
sapatos

Reputation: 1304

C++ String to double atof conversion losing precision?

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

Upvotes: 6

Views: 7379

Answers (3)

Raph Levien
Raph Levien

Reputation: 5218

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.

Upvotes: 3

wheaties
wheaties

Reputation: 35970

The function atof creates a double. See here. Your problem is that the %g returns either the shorter of float or scientific notation. See here. Also note, that you're adding the in * notation which signifies that there is an expected truncation in the number of printed characters.

Upvotes: 1

sth
sth

Reputation: 229593

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

Upvotes: 2

Related Questions