Parse Integer

From SwiftAPI

(Redirected from JavaScript parseInt)
Jump to: navigation, search

Contents

C

#include <stdlib.h>
 
char* s = "42";
int i = atoi(s);
// i == 42

C++

#include <string>
#include <sstream>
using namespace std;
 
string s = "42";
istringstream iss(s);
int i;
iss >> i;
// i == 42

C#

string s = "42";
int i = Int32.Parse(s);
// i == 42

Java

J2SE 1.4.2

String s = "42";
int i;
try {
    i = Integer.parseInt(s);
}
catch(NumberFormatException e) {
 
}
// i == 42

JavaScript

var s = "42";
var i = parseInt(s);
// i == 42

alternately:

var s = "42";
var i = +s;
// i == 42

Objective-C

developer.apple.com

@property(readonly) int intValue
NSString *s = @"42";
int i = s.intValue;
// i == 42

Perl

There is no need. Strings and numbers are interchangeable. Strings are automatically converted to numbers when used in arithmetic. php.net

$s = "42";
$i = 0 + $s;
# $i == 42

Note that however it stops at the first invalid character, and does not cause an error if the string contains invalid characters (it does produce a warning if "warnings" is on though):

$s = "42abc123";
$i = 0 + $s;
# $i == 42
 
$s = "xyz42";
$i = 0 + $s;
# $i == 0

PHP

There is usually no need. Strings and numbers are interchangeable. Strings are automatically converted to numbers when used in arithmetic.

$s = "42";
$i = (int)$s;
// $i == 42

Python

docs.python.org

s = "42"
i = int(s)
# i == 42

Ruby

Parses as much of string as valid, or returns 0 if entire string is invalid. Never raises exception. ruby-doc.org

s = "42"
i = s.to_i
# i == 42

Parses all of string; raises exception if any of it is invalid. ruby-doc.org

s = "42"
i = Integer(s)
# i == 42

Swift

let s = "42"
let i = s.toInt()
// i == Optional(42)
Personal tools