C++不是我的語言,所以原諒這個簡單的問題。我從字符串轉換爲雙精度時失去精度,任何人都可以幫忙嗎?C++字符串雙重atof轉換失去精度?
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
我已經在memset的函數%F發揮然而,這給了提前131663.510000
感謝。
Sapatos
如果我需要這個確切的金額,我會考慮使用定點。在C++方面,我確信除了atof之外,還有更好的方法將字符串轉換爲double。如果你認爲問題出在那裏,sprintf()是另一種C方法。作爲評論,因爲我沒有在這裏爲你準確的答案。 –
@Michael:雖然體積很大,但可以使用流,C++ 0x引入了特定的「stof」(以及整個系列)指令作爲標準庫的一部分。 –