About operators 199
About the conditional operator
The conditional operator is a ternary operator, which means that it take three operands. The
conditional operator is a short-hand method of applying the
if..else conditional statement:
For information on using the conditional operator and an example, see “About the
conditional operator and alternative syntax” on page 152.
Using operators in a document
In the following example, you use the Math.round() method to round calculations to an
arbitrary number of decimal places. This method rounds the value of the
x parameter up or
down to the nearest integer, and then returns the value. After you slightly modify the
ActionScript, you can make Flash round numbers to a certain number of decimal
places instead.
In the next example, you also use the division and multiplication operators to calculate a user’s
score based on the number of correct answers divided by the total number of questions that
are asked. The user’s score can multiply by a number and display to get a score between 0%
and 100%. Then you use the addition operator to concatenate the user’s score into a string
that is displayed in the Output panel.
To use operators in ActionScript:
1. Create a new Flash document.
2. Type the following ActionScript on Frame 1 of the main Timeline:
var correctAnswers:Number = 11;
var totalQuestions:Number = 13;
//round to the nearest integer
//var score:Number = Math.round(correctAnswers / totalQuestions * 100);
//round to two decimal places
var score:Number = Math.round(correctAnswers / totalQuestions * 100 *
100) / 100;
trace("You got " + correctAnswers + " out of " + totalQuestions + "
answers correct, for a score of " + score + "%.");
Operator Operation performed
?:
Conditional