Weird with numbers!

Well I have this code but somehow it just make weird thing
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
double num = 0.07;
	while(num > 0 && num < 0.99999999999999999)
	{
		std::cout<<"*******************"<<std::endl;
		std::cout<<"original number = "<<num<<std::endl;
		short s = 0;
		
		num*=(double)10;
		std::cout<<"\noriginal number*10 = "<<num<<std::endl;
		
		s = num;
		std::cout<<"\noriginal number to int = "<<s<<std::endl;

		num = num - s;
		std::cout<<"\noriginal number*10 - int = "<<num<<std::endl;

		std::cout<<"*******************"<<std::endl;
		if (s==7)
			break;
	}


Output

*******************
original number = 0.07

original number*10 = 0.7

original number to int = 0

original number*10 - int = 0.7
*******************
*******************
original number = 0.7

original number*10 = 7

original number to int = 7

original number*10 - int = 8.88178e-016          <-- Here this is weird i supposed it gives 0
*******************
floating point numbers are approximations.

8.88178e-016 is equal to 0.000000000000000888178 which is very close to zero.

This site explains why this happens pretty well:
http://www.parashift.com/c++-faq-lite/floating-pt-errs.html


Basically... if you need numbers to be exact... don't use floating point.
What to use then/?
depends on what you need.
well i want to convert a decimal number into string, basiccally want numbers to be exact :p
Last edited on
So, you want to convert 0.9997 into a string? I didn't understand, you can cast into integer or use some rounding method, followed by conversion into string.

To compare two doubles, compute the algebraic distance between them.
If i have 0.9997 , I want to string be "0.9997".
4 points of decimal shouldn't be a problem.

1
2
3
double v = 0.9997;

cout << setprecision(4) << fixed << v;



EDIT:

or if you want a string object:

1
2
3
4
5
6
stringstream ss;
ss << setprecision(4) << fixed << v;

string yourstring = ss.str();

cout << yourstring;
Last edited on
Thanks for help, anyway I will just make it with less digits.
Topic archived. No new replies allowed.