开发者

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

开发者 https://www.devze.com 2023-01-28 10:19 出处:网络
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:

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;
 }
 ret开发者_开发技巧urn 0;
}

the values i'm getting in the doubles where i save this function result are like 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.

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, i.e.

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

0

精彩评论

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