Please help...I am having a problem with comparing double values in C++. I have stumble across this issue when my sorting algorithm tries to compare double values to check whether a < b / a > b. Based on the comparison result my sorting algorithm does sorting by ascending or sorting in descending order.

However when I have something like the following double value comparison it yields different behavior.


Example:

double dValue1 = 10.5
double dValue2 = 10.10;


If i'm going to compare using > operator in C++ turns out the result is different than what I am expecting.

10.5 is compared to 10.1 --> looks to me there's a rounding issue here since it doesn't account for the floating point precision.

Hope there's someone who could share his/her idea on how to fix this bug.

I mean ultimately, I would expect that 10.10 should be greater than 10.5 when we compare both double values.


Thanks,
alein

Recommended Answers

All 5 Replies

Why should 10.1 be greater than 10.5?

Can you add your code to the post so that there is more clarity?

> I mean ultimately, I would expect that 10.10 should be greater than 10.5 when we compare both double values.
Huh?

So if I wrote the same values as
10.10 and 10.50
would that change anything for you?

Because it doesn't change anything for the compiler, or the numbers.

Hello,

No, it doesn't change actually when comparing two double values 10.5 and 10.10 actually yields the same comparison result as 10.50 and 10.10.

I supposed the problem was that in my program the 10.5 which is actually a version number previously stored as a string before conversion to double was already having that notation. I thought it should be 10.05 because the 10.5 in double lexically means 10.50 isn't it?

thanks,
alein

No, what the problem is your understanding of numbers.

10.1 is identical to 10.10 is identical to 10.1000000
Each is 10 and 1 tenth. It doesn't matter how many zeros you add.

Therefore, 10.5 (10 and 5 tenths) > 10.10000000

commented: :) +19

Thank you all for your feedback now I understand the semantics of numbers represented as double values.

Cheers,
alein

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.