I needed to convert a float to a string with only two decimal places (currency), so I found itoa on this site. I got that working without any problems. Here's my test code:
1 2 3
float c=3.12;
int d=(c*100);
cout<<c<<"\n"<<d;
For some strange reason, that seemingly simple code returns d as "311" instead of "312" like I would expect. I changed c to different values like 3.22 and 3.29 and the program behaves as expected. It only has a strange result when converting that specific number. Can anyone tell me what is going on here and how to fix it?
floating point numbers are not entirely accurate. The way they are stored means that 3.12 is stored as something like 3.1111111119 etc. Thus when converting to an int. The last digits are not rounded, but simply dropped off.
3.111111999 (3.12) becomes 311.
If you want to convert a float to a string with only 2 decimal places. You can use a string stream to achieve this.