2011-01-24 103 views
5

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

+0

如果我需要這個確切的金額,我會考慮使用定點。在C++方面,我確信除了atof之外,還有更好的方法將字符串轉換爲double。如果你認爲問題出在那裏,sprintf()是另一種C方法。作爲評論,因爲我沒有在這裏爲你準確的答案。 –

+1

@Michael:雖然體積很大,但可以使用流,C++ 0x引入了特定的「stof」(以及整個系列)指令作爲標準庫的一部分。 –

回答

3

問題是您的%g格式運算符,它沒有足夠的精度指定。您可能需要%.2f,它會在小數點後打印兩位數字。

+0

thansk that works – sapatos

2

sprintf%g格式說明默認爲打印6個顯著數字。如果您想了解更多,您可以明確指定多少應打印:

sprintf(cAmount,"%.8g*",dTotal); 
1

功能atof創建一個雙。請參閱here。你的問題是%g返回較短的浮點數或科學記數法。見here。另請注意,您正在添加*表示法,表示打印字符數有預計的截斷。

+0

*是一個拼寫錯誤:( – sapatos

+0

'*'符號需要在轉換說明符之前有任何影響......因爲它只是作爲普通字符打印出來 –