Typecasting
From CodeCodex
Contents |
[edit] Implementations
[edit] C++
int x = 2 string y = (string)x
[edit] C#
int x = 2; string y = (string)x;
[edit] Java
double doubleName = 3; int intName = (int)doubleName; // intName becomes == 3 double anotherDoubleName = 3.3; int anotherIntName = (int)anotherDoubleName; //anotherIntName becomes == 3, not 3.3
[edit] PHP
$x = -2.2; $y = (int)$x; // $y = -2
[edit] OCaml
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"
[edit] Perl
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
[edit] Python
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
[edit] Ruby
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
[edit] Visual Basic .Net
dim x as integer = 2 dim y as string = ctype(x,string)

