开发者

C++ String to double atof conversion losing precision?

开发者 https://www.devze.com 2023-02-06 03:16 出处:网络
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?

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 + dAccrue开发者_Go百科dInterest;

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消