Reputation: 632
I want to write a function that accepts either an int or a Number as a parameter and does different things depending on what type it is. My first question is what to use in the signature, Object or Number? I was thinking Number because it covers both int and Number.
function myFunction(p:Number):void { //Should p be of type Object or Number?
if (p is int) trace("Parameter is int.");
else if (p is Number) trace("Parameter is Number.");
}
The problem is I want it to be classified as a Number if the parameter has a decimal point like 1.00. That will still come up as int. Does anyone have any ideas how to do that? I suppose I could convert p to a String and then check to see if it contains a decimal point, but I was hoping there was an easier way.
Upvotes: 0
Views: 126
Reputation: 4750
The main problem I see is with the following sentence:
The problem is I want it to be classified as a Number if the parameter has a decimal point like 1.00.
Let's say we have an int
variable called x
, and we set it to 1
. Does it look like 1
, 1.00
, or 1x10^-1
? The answer is always no. Even if somebody were to type this:
myFunction(1.00);
the number still wouldn't actually look like anything. It's just the number one. Its only representation basically is however it looks in the actual machine bit representation (either floating point-style or just 000...001
).
All it is is a number - whether stored in a Number
variable or an int
variable. Trying to convert it to a String
won't help, as the information isn't there to begin with. The closest you're going to be able to come to this is pretty much going to be to use a String
as the parameter type and see if somebody calls myFunction("1")
or myFunction("1.00")
.
Only do something like this if you really have to, due to the wide range of stuff that could actually be stored in a String
. Otherwise your is
keywords should be the best way to go. But whichever one you choose, do not use an Object
or untyped parameter; go with either a String
or (much more preferably) a Number
.
Upvotes: 1