简体   繁体   English

C ++字符串加倍atof转换会失去精度?

[英]C++ String to double atof conversion losing precision?

C++ is not my language so forgive this simple problem. C ++不是我的语言,所以请原谅这个简单的问题。 I'm losing precision in an atof conversion from string to double, can anyone help? 我在从字符串到双精度的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

I've played with %f in the memset function however this gives 131663.510000 我在memset函数中玩过%f,但这给出了131663.510000

Thanks in advance. 提前致谢。

Sapatos 萨帕托斯

The problem is your %g format operator, which isn't specified with enough precision. 问题是您的%g格式运算符,没有指定足够的精度。 You might want %.2f instead, which prints two digits after the decimal point. 您可能需要%.2f ,它在小数点后输出两位数。

The sprintf %g format specifier defaults to printing six significant digits. sprintf %g格式说明符默认为打印六个有效数字。 If you want more, you can explicitly specify how many should be printed: 如果需要更多,可以显式指定应打印的数量:

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

The function atof creates a double. 函数atof创建一个double。 See here . 这里 Your problem is that the %g returns either the shorter of float or scientific notation. 您的问题是%g返回浮点数或科学计数形式中的较短者。 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. 另请注意,您正在添加in *表示表示预期的打印字符数截断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM