Typecasting

From CodeCodex

Implementations[edit]

C++[edit]

 int x = 2
 string y = (string)x

C#[edit]

 int x = 2;
 string y = (string)x;

Java[edit]

double doubleName = 3;

int intName = (int)doubleName;  
  // intName becomes == 3


double anotherDoubleName = 3.3;
int anotherIntName = (int)anotherDoubleName;  
  //anotherIntName becomes == 3, not 3.3

OCaml[edit]

OCaml's strong static type system disallows arbitrary conversions of values between types. Instead, one must use either the built-in conversion functions or write additional functions (e.g. for your own data structures). For example, the built-in string_of_int function converts an int to a string:

# string_of_int 1234;;
- : string = "1234"

Perl[edit]

Strong typing is for people with weak nerves. Types do not need to be cast in Perl, just use the thing in question in appropriate context (numeric, stringification, bool, list, …).

my $i_am_a_string_initially = '123 foo';
$i_am_a_string_initially   -= 23;       # 100
my $i_am_a_number_initially = 123;
$i_am_a_number_initially   .= 'bar';    # 123bar

PHP[edit]

  $x = -2.2;
  $y = (int)$x;
  // $y = -2

Python[edit]

All the built-in types have corresponding functions of the same name ("int", "float", "str", etc.) that convert to that type.

x = -2.2
y = int(x)
# y = -2

Ruby[edit]

x = 2.2
i = x.to_i      #=> 2
s = x.to_s      #=> "2.2"
j = s.to_i      #=> 2
y = s.to_f      #=> 2.2

Visual Basic .Net[edit]

 dim x as integer = 2
 dim y as string = ctype(x,string)