strange result when converting float to int

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.

This might be of use to you:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <sstream>
#include <iostream>
#include <string>
#include <iomanip>

using namespace std;

string convertFloat(float value) {
  std::ostringstream o;
  o.setf(ios::fixed,ios::floatfield);
  if (!(o << setprecision(2) << value))
    return "";
  return o.str();
}


int main() {
  cout << "1. " << convertFloat(133.11123) << endl;

  return 0;
}
Topic archived. No new replies allowed.