This content has been marked as final. Show 9 replies
> I've got a 5 digit number, for example 12345. I want to
> extract the second last number, in the example it would
> be 4. I'm sure there's a way to do this,
If I had to do this, I would convert that number to a string and use
String methods on it.
var n:Number = 12345;
var s:String = n.toString();
In the above, the variable n represents your original number. The s
variable is that same number, as a string. Finally, the String.charAt()
method is fed a parameter of 3 to pull out the fourth character from that
string. Why does 3 pull out character four? This is just "one of those
things" you have to get used to with programming. In many cases,
ActionScript counts series of things from zero, rather than one. So 0 is
the first, 1 is the second, and so on.
You can see for yourself in the String.charAt() entry of the
ActionScript 2.0 Language Reference. See the "String class" entry itself
for other string methods (methods are a things a particular object can do;
properties are the characteristics it has and events are the things it can
Adobe Community Expert
Dev blog, http://www.quip.net/blog/
"Luck is the residue of good design."
for example you can convert the number to string, than create a substring of it extracting the requested digits and then create a number again from that string. :) you can write a flexible function for this task, something like the following... (you can copy the whole code below to an empty flash document into the first frame as a frame action and just test the movie to see results in the trace panel)
Thank you! It really helped me a lot :)
how about this
num1 = 12345;
num2 = Math.floor((num1%100)/10);
ok, this works - in this special case and maybe in some other cases too still it's not a good solution because it works only in special cases! the function i submitted is more generic and uses no math therefore it returns the correct digit(s) in every case! think about it or try your code with other combination of digits to see what i mean.
i think ggshow's method is great!
very short... very logical...
If you always want the second to last digit no matter how long the number is the easiest way is to cast the number to a string and use the substr() function with a negative parameter for the start and a length of 1 like so:
var someNumber:Number = 12345;
var tempString:String = someNumber.toString();
trace(tempString.substr(-2,1)); //output: 4
a negative start number will start the substring from the end of the string instead of the beginning
aghh... ok! i see now!! :) i was fool a bit! gg's code is good for every case if you want to extract the second last digit. ok, nice one. ;)
num1 = 12345;
num2 = Math.floor(num1/10%10);