Unary Plus (+)

Summary

Converts an expression to an int.

Syntax

+expression

Parameters

expression
A valid expression.

Description

The unary plus (+) operator precedes an expression and attempts to convert the evaluated expression value to an int. For valid types, this has the same effect as an explicit cast to int:

1
2
3
4
5
string s = "100";
 
int x = (int) s;
// is equivalent to:
int y = +s;

When the unary plus operator is applied to a non-external string, decimals will be truncated. In order to preserve decimal numbers, convert to a float or double. 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 plus (+) expression will be 0 (zero).

Differences to JavaScript

In JavaScript, the unary plus (+) 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