Removal of decimal place in float

I am trying to make a simple function that 'integrates' floats. Basically 0.3857
Becomes 3857. 2.45 becomes 245 and so on. But my code sometimes just goes mad and produces some absolutely insane results.

1
2
3
4
5
  void integrate(float &num)
{
    while(int(num)!=num)
        num*=10;
}
The problem is that many numbers cannot be stored exactly as a floating point value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <iomanip>

void integrate(float &num)
{
    while(int(num)!=num)
        num*=10;
}

int main()
{
	float values[] = 
	{
		0.125,
		0.3857,
		2.45,
		0.24
	};
	
	std::cout << std::setprecision(100);
	
	for (float value : values)
	{
		std::cout << value << " => ";
		integrate(value);
		std::cout << value << '\n';
	}
}
0.125 => 125
0.3856999874114990234375 => 3857
2.4500000476837158203125 => 245
0.23999999463558197021484375 => 23999998

As you can see, if you're lucky it can work out the way you want even when the number cannot be stored exactly, but sometimes you are not so lucky. Floating point values are best used as approximations only. If you need the numbers to be exact you probably should use some other way of storing them.
Last edited on
Topic archived. No new replies allowed.