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.


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.


8 Years
Discussion Span
Last Post by agurrea

Why should 10.1 be greater than 10.5?

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

Edited by thomas_naveen: asked for code


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

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.



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?



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

Votes + Comments

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


This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.