Unary Negation (-)

Summary

Converts an expression to an int and negates its integer value.

Syntax

-expression

Parameters

expression
A valid expression.

Description

The unary negation (-) operator precedes an expression and attempts to convert the evaluated expression value to an int and negates its integer value. In other words, if the integer value is positive, it will become negative; if the integer value is negative, it will become positive.

1
2
3
4
5
string positive = "1";
string negative = "-1";
 
int x = -positive; // x == -1
int y = -negative; // x == 1

When the unary negation operator is applied to a non-external string, decimals will be truncated. In order to preserve decimal numbers, convert to a float or double first. For example:

1
2
3
4
string s = "100.5";
 
int x = -s;               // x is -100
double y = -s.toDouble(); // y is -100.5

If the conversion fails, the evaluated value of the unary negation (-) expression will be 0 (zero).

Differences to JavaScript

In JavaScript, the unary negation (-) operator will return a number of type number (equivalent to JS++'s double type). This allows conversions of strings to number without truncation of decimal digits; however, invalid conversions result in NaN. In order to avoid NaN errors, a design decision was made to convert to int rather than double for JS++. Where conversions to types other than int are desired, type casting can be used.

Examples

Converting Strings to int
1
2
string s = "100";
int x = -s;
Converting Externals to int
1
2
3
external s;
 
int x = -s;

See Also

Share

HTML | BBCode | Direct Link