### Starnge validation problem with float and double

Hi,

Below is my code snippet which seemed to work fine but then I found the following problem:

When I type in 2.22 for example then the function returns 2.2200000000000002,
when I type in 6.66 then function returns 6.6600000000000001 !!!!

When I debug then it is clearly visible that:
input = "2.22"
but MyNumber = 2.2200000000000002

It seems that something goes wrong during myStream >> myNumber conversion.
Any idea how to solve this or what can be the problem???

Here is the code:
 ``12345678910111213141516171819`` ``````double MyCin( string MyText ) { // This function prints out the text in the parameter to the screen // then gets a number and checks it, then returns the number double myNumber = 0; string input = ""; // Get a number safely. while (true) { cout << MyText; getline(cin, input); // This code converts from string to number safely. stringstream myStream(input); if (myStream >> myNumber) break; cout << "Invalid number, please try again" << endl; } return myNumber; };``````

This is how I call the function:
a1 = MyCin("Please input a1= ");

The computer stores the number in a binary base.
You wrote them in a decimal base.

Suppose that you want to write the result of 1/3
You can't in base 10, however it is simply 0.1 in base 3.
That's all.
decimal in computer is discrete, it can not be stored accurately.
Thanks for the answers, I have found out to and all difficulties how to compare floating numbers:)
I know now that fmod(f1,f2) does not work always correctly:(
Any better way to calculate modulus of two floating number?

I know one way first to convert to integer then calculate modulus but any other good way?

example fmod(f1,f2, digit)

I want something like:

f1 = 6.66
f2 = 2.22

remainder = fmod(f1,f2,2)

where remainder will be zero!!!

So any really working fmod for floating numbers??
if you want to calculate precisely, string instead of double, but it's more complex :) good luck!
Thanks
fmod is working. It is just that the numbers that you pass to fmod isn't exactly 6.66 and 2.22. More precisely (but not exactly) 6.6600000000000001421 and 2.2200000000000001954. So to calculate f1 mod f2 we just subtract f2 from f1 until we get a value less than f2.

6.6600000000000001421 - 2.2200000000000001954 = 4.4399999999999999467
4.4399999999999999467 - 2.2200000000000001954 = 2.2199999999999997513
Now we stop because we have got a value less than f2.
Topic archived. No new replies allowed.