PDA

View Full Version : Solved: FYI: Educational moment



Imdabaum
01-19-2010, 04:06 PM
:think: If I simply use the following code:

rs2.Fields("AmountOfBlahs") = rs.Fields(blah) * rs.Fields(blahblah) * (rs.Fields(blahdyblahblah)/100)

rs2 gets a value appended to the field and everything works fine and dandy.


But now let's say I have the following variables:
fee
timeframe
rate

I set each of these according to a record field because personally (be it laziness or early onset arthritis) I don't like typing rs.Fields(Blah) & rs.Fields(blahblah) & rs.Fields(blahdyblahblah) over and over again. Yes I do use these values repeatedly throughout multiple processes.
I end up with


Dim fee as Integer
Dim timeframe as Integer
Dim rate as Double
fee = rs.Fields(blah)
timeframe = rs.Fields(blahblah)
rate = rs.Fields(blahdyblahblah)/100

rs2.Field(AmountOfBlah) = fee * timeframe * rate 'breaks


This gives me an overflow error.

If I do a little switch-a-roo.

Dim fee as Integer
Dim timeframe as Integer
Dim rate as Double
fee = rs.Fields(blah)
timeframe = rs.Fields(blahblah)
rate = rs.Fields(blahdyblahblah)/100

rs2.Field(AmountOfBlah) = fee * rate * timeframe 'fixes


Code executes perfectly.

Educators: Can you explain why this is the case? Not sure whether to mark this solved as switching around the values did solve the problem. But the question is nevertheless still out there.

CreganTur
01-20-2010, 10:31 AM
Educators: Can you explain why this is the case? Not sure whether to mark this solved as switching around the values did solve the problem. But the question is nevertheless still out there.

An overflow error occurs when you try to shove a number into a variable of a certain type when the number is larger than the type's limits. You've got a double that you're multiplying by two ints. If the result of this calcualtion is larger than what an Int can handle, you'll get the error.

Also, your calculations will be done in order:
rs2.Field(AmountOfBlah) = fee * timeframe * rate 'breaks
(int)fee * (int)timeframe will happen first. That result will then be multiplyed by (double)rate- this will cause the result of the calculation to be a double data type. I am guessing that rs2.Field(AmountOfBlah) is expecting an int data type, so passing a double into an int is also causing an error. Using casting can help you avoid this error.

HTH:thumb

Imdabaum
01-21-2010, 08:38 AM
Brilliant. Thanks.