Flash / Flex / ActionScript/Data Type/Number parse
Содержание
- 1 Adding strings and numbers: the compiler will convert the numbers to strings rather than the other way around.
- 2 Converting a string containing only numerical data
- 3 Converting to a Number with Precision: parseInt() and parseFloat().
- 4 If you omit the second parameter, ActionScript attempts to parse the number value using the most appropriate base.
- 5 Parse number values from strings with bases other than 10 using the parseInt() function.
- 6 Trying to cast any other value will result in a nasty NaN (Not a Number) value being assigned instead:
Adding strings and numbers: the compiler will convert the numbers to strings rather than the other way around.
<source lang="java">
package{
import flash.display.Sprite; public class Main extends Sprite{ public function Main(){ var a:Number = 2 + "2"; trace(a); // Displays: 22 } }
}
</source>
Converting a string containing only numerical data
<source lang="java">
package{
import flash.display.Sprite; public class Main extends Sprite{ public function Main(){
var shoeSize:String = "12"; var iq:Number = Number(shoeSize); trace(iq); } }
}
</source>
Converting to a Number with Precision: parseInt() and parseFloat().
<source lang="java">
package{
import flash.display.Sprite; public class Main extends Sprite{ public function Main(){ var nOne:Number = parseInt("13.3"); // 13 var nTwo:Number = parseFloat("13.3"); // 13.3 var nThree:Number = parseInt("54"); // 54 var nFour:Number = parseFloat("54"); // 54 } }
}
</source>
If you omit the second parameter, ActionScript attempts to parse the number value using the most appropriate base.
<source lang="java">
package{
import flash.display.Sprite; public class Main extends Sprite{ public function Main(){ var nOne:Number = parseInt("0101"); // returns 65 trace(nOne); var nColorValue:Number = parseInt("0xFF0000"); trace(nColorValue); } }
}
</source>
Parse number values from strings with bases other than 10 using the parseInt() function.
<source lang="java">
package{
import flash.display.Sprite; public class Main extends Sprite{ public function Main(){ var nOne:Number = parseInt("11", 10); // 11 var nTwo:Number = parseInt("11", 2); // 3 var nThree:Number = parseInt("gg", 17); // 288
} }
}
</source>
Trying to cast any other value will result in a nasty NaN (Not a Number) value being assigned instead:
<source lang="java">
package{
import flash.display.Sprite; public class Main extends Sprite{ public function Main(){ var dialASong:Number = Number("(718)"); trace(dialASong); // Displays: NaN } }
}
</source>