Problem comparing text box value with numeric value

  • Thread starter Thread starter Sunny
  • Start date Start date
S

Sunny

Very strange! My application was working fine and suddenly it started the
problem. My problem is comparing value in text box with database table field
value. My textbox format property set with Fixed and with decimal 2. The
value in text box is 100.00 and now one of my table field value is 100.00.
and it can not read both value same. I have following code in my
application:

nFldVal = rs!tblFld ' stores 100.00 in nFldVal
IF txtMyBox <> MyField then
'This code should not execute since both value same. But it display
following value.
MsgBox("Value does not match")
else
MsgBox("Value match")
endif


If I use following code, it works fine.
IF VAL(txtMyBox) <> MyField then
MsgBox("Value does not match")
else
'This time it displays this message
MsgBox("Value match")
endif

What am I doing wrong?

Thanks.
 
Hi Sunny,

If I understand you right, this is a common and expected occurence when
comparing floating point values (e.g. the Single or Double field types).
It happens because not all decimal numbers can be stored exactly in the
binary format used by these data types.

You can avoid the problem by using the Long, Integer or Currency data
types, which store and compare exact values. If you have to use floating
point types, one common way of working round it is as follows. Instead
of testing whether two values are identical, test whether the difference
between them is so small that they are near enough identical for your
purposes. So instead of using
If txtMyBox = MyField Then ...
I'd use something like
If Abs(txtMyBox - MyField) > 0.0000001 Then ...
 
Thanks John for your suggestion.
John Nurick said:
Hi Sunny,

If I understand you right, this is a common and expected occurence when
comparing floating point values (e.g. the Single or Double field types).
It happens because not all decimal numbers can be stored exactly in the
binary format used by these data types.

You can avoid the problem by using the Long, Integer or Currency data
types, which store and compare exact values. If you have to use floating
point types, one common way of working round it is as follows. Instead
of testing whether two values are identical, test whether the difference
between them is so small that they are near enough identical for your
purposes. So instead of using
If txtMyBox = MyField Then ...
I'd use something like
If Abs(txtMyBox - MyField) > 0.0000001 Then ...
 
Back
Top