简体   繁体   English

将char *转换为双精度点,最多2个位

[英]convert char* to double with max 2 places after the point

i'm reading tokens from file, it enters the char pointers perfectly as it comes in the file, but after sending it to this function: 我正在从文件读取令牌,它完全进入字符指针,就像它在文件中一样,但是将其发送到此函数后:

double CharToDouble(char *ptemp)
{
 if(ptemp != NULL)
 {
  if(ptemp[0] == '0')
   return atof(ptemp);
  else
   return atof(ptemp)/100;
 }
 return 0;
}

the values i'm getting in the doubles where i save this function result are like 0.6600000000001 0.280000000000000000 我在保存此函数结果的双打中得到的值就像0.6600000000001 0.280000000000000000

and stuff like that, i want it to be ecaxtly as in the char*.. it's money issues, in cents. 像这样的东西,我希望它像字符*那样令人费解。这是金钱问题,以美分计。

any idea? 任何想法?

If it's a currency, multiply by 100 and round down to an integer, so instead of 123.45, you have 12345. 如果是货币,则乘以100并四舍五入为整数,因此您有12345,而不是123.45。

Note: Float and Double are accurate only up to a certain precision (machine precision), because not every real number can be encoded in the floating point format. 注意:浮点数和双精度仅在达到一定精度(机器精度)时才是精确的,因为并非每个实数都可以浮点格式进行编码。

When you're only interested in output of the correct format, you must use the correct printf command, ie 当您只对正确格式的输出感兴趣时,必须使用正确的printf命令,即

double currency_value = 9.95;
printf("Currency: %.2f", currency_value)

Look up "Format String" to learn more. 查找“格式字符串”以了解更多信息。 The %.2f says that I want a floating point number with a fixed position after the comma (f) and that this position should be the second number after the comma (2). %.2f说我想要一个在逗号(f)之后具有固定位置的浮点数,并且该位置应该是在逗号(2)之后的第二个数字。

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

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