S2 Cookbook: Numbers

From Dreamwidth Notes
Revision as of 02:32, 8 August 2010 by Foxfirefey (Talk | contribs)

Jump to: navigation, search

Arithmetic

Comparing two numbers to see if they are equal or one is lesser/greater

Seeing if a number is odd or even

The mod operation, signified by the % symbol, can tell you if a number is odd or even. Mod a number by 2, and if the result is equal to 1, the number is odd. If the result is equal to 0, the number is even.

var int odd = 8;
 
# prints "Odd"
if( $odd % 2 == 1 ) {
    print "Odd";
} else {
    print "Even";
}
 
var int even = 6;
 
# prints "Even"
if( $even % 2 == 0 ) {
    print "Even";
} else {
    print "Odd";
}

Pad a number with 0s to a certain number of digits

Use the zeropad function to get a string that's padded with 0s to a certain number of digits:

var int label = 1;
# 001
print zeropad($label, 3) + "<br />";
 
# works on strings that are integers, too!
var string fake_int = "2";
# 0002
print zeropad($fake_int, 4) + "<br />";
 
# this won't work because "A2" won't convert to an integer correctly
var string fake_label = "A2";
# 000
print zeropad($fake_label, 3) + "<br />";

Get a random number

You can create random numbers using the two kinds of rand functions:

# returns a random number between 1 and 10
var int pick = rand(10);
# returns a random number between 11 and 20
var int pick2 = rand(11, 20);
# returns a random number between the two random numbers
var int pick3 = rand($pick, $pick2);

Convert a string to an integer

Convert an integer to a string