Conversion Between Data Types

   Print  Previous  Next

Introduction

If there are different data types within an expression, they must be converted into the same type. MADRIX Script does those conversions implicitly, but in most times a warning will be displayed in the compiler message box of the Script Editor. It is also possible to do those conversions explicitly writing the destination data type in brackets before the expression, like this:

int i = (int)GetSpeed(); //if the speed was 42.8, i is now 42

string s = (string)i;    //s now consists of the characters "42"

 

GetSpeed returns a float value which has to be converted into int before it can be assigned to i. Be aware that the positions after the decimal point are abridged. Afterwards, the numeric value is assigned to i.

The following table shows an overview over possible conversions:

 

int

float

string

structure

bool

expressions

int

-

Converts the value to float.

Converts the value to string: e.g. 12 = "12".

N/A

Is true if the value is not 0.

float

Converts the value to int. The decimal part is truncated without rounding off.

-

Converts the value to string: e.g. 12.34 = "12.34"

N/A

Is true if value is not 0.

string

If the string is a number, the string is converted into an integer value, otherwise it results in 0.

-

N/A

Is true if string is not empty.

structure

N/A

Conversion between different structures: N/A.

N/A

 

Implicit Conversions With Math Expressions

If one of the two operands of a math expression is of the type float and the other is of the type int, the int value is converted to float and the expression results in the data type float.

If one of the two operands of a math expression is of the type string, the other operand is converted into a string and the expression results in a string.

If the conversion is not possible according to the table above, the compiler prints an error and you have to correct the expression. Here are some examples of expressions and their results:

Expression

Result

Explanation

int i = 3 / 4 * 2

0

3 / 4 is an integer operation and results in 0. Hence, the whole expression results in 0.

3 / 4.0 * 2

1.5

Because 4.0 is a float value, 3 will be converted into float, too. In this way, 3 / 4.0 results in 0.75. Then, 2 is also converted into float since the other operand is of the type float. And the result is therefore 1.5.

string test = "It is " + 9 + " o'clock."

"It is 9 o'clock."

Since the first operand is a string, 9 is also converted into a string and concatenated with the first string.

string test = 2 + 3 + "40"

"540"

2 & 3 are both integer and will be added up due to an integer operation. The second operation has a string as operand and therefore the other operand will be converted into a string and both are concatenated together.