Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - comparison of two "Real" number variables

I have problem with comparison of two variables of "Real" type. One is a result of mathematical operation, stored in a dataset, second one is a value of an edit field in a form, converted by StrToFloat and stored to "Real" variable. The problem is this: 121,97 not equal to 121,97

As you can see, the program is trying to tell me, that 121,97 is not equal to 121,97... I have read this topic, and I am not copletely sure, that it is the same problem. If it was, wouldn't be both the numbers stored in the variables as an exactly same closest representable number, which for 121.97 is 121.96999 99999 99998 86313 16227 83839 70260 62011 71875 ?

Now let's say that they are not stored as the same closest representable number. How do I find how exactly are they stored? When I look in the "CPU" debugging window, I am completely lost. I see the adresses, where those values should be, but nothing even similar to some binary, hexadecimal or whatever representation of the actual number... I admit, that advanced debugging is unknown universe to me...

Edit: those two values really are slightly different.

enter image description here

OK, I don't need to understand everything. Although I am not dealing with money, there will be maximum 3 decimal places, so "currency" is the way out

BTW: The calculation is:

DATA[i].Meta.UnUsedAmount := DATA[i].AMOUNT - ObjQuery.FieldByName('USED').AsFloat;

In this case it is 3695 - 3573.03

like image 652
j.kaspar Avatar asked Mar 19 '16 14:03

j.kaspar


1 Answers

For reasons unknown, you cannot view a float value (single/double or real48) as hexadecimal in the watch list.

However, you can still view the hexadecimal representation by viewing it as a memory dump.
Here's how: Add the variable to the watch list.
Right click on the watch -> Edit Watch...
View it as memory dump

enter image description here

Now you can compare the two values in the debugger.

Never use floats for monetary amounts
You do know of course that you should not use floats to count money.
You'll get into all sorts of trouble with rounding and comparisons will not work the way you want them too.
If you want to work with money use the currency type instead. It does not have these problems, supports 4 decimal places and can be compared using the = operator with no rounding issues.

In your database you use the money or currency datatype.

like image 132
Johan Avatar answered Sep 17 '22 07:09

Johan