Parse Float
From SwiftAPI
(Redirected from JavaScript parseFloat)
Contents |
C
#include <stdlib.h> char* s = "3.14"; double f = atof(s); // f == 3.14
C++
#include <string> #include <sstream> using namespace std; string s = "3.14"; istringstream iss(s); double f; iss >> f; // i == 3.14
Java
String s = "3.14"; float f; try { f = Float.parseFloat(s); } catch(NumberFormatException e) { } // f == 3.14
JavaScript
var s = "3.14"; var f = parseFloat(s); // f == 3.14
alternatively:
var s = "3.14"; var f = +s; // f == 3.14
Objective-C
@property(readonly) float floatValue
NSString *s = @"3.14"; float f = s.floatValue; // f == 3.14
Perl
There is no need. Strings and numbers are interchangeable. Strings are automatically converted to numbers when used in arithmetic.
$s = "3.14"; $f = 0 + $s; # $f == 3.14
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 = "3.14abc159"; $f = 0 + $s; # $f == 3.14 $s = "xyz3.14"; $f = 0 + $s; # $f == 0
PHP
There is usually no need. Strings and numbers are interchangeable. Strings are automatically converted to numbers when used in arithmetic.
$s = "3.14"; $f = (float)$s; // $f == 3.14
Python
s = "3.14" f = float(s) # f == 3.14
Ruby
Parses as much of string as valid, or returns 0 if entire string is invalid. Never raises exception. ruby-doc.org
s = "3.14" f = s.to_f # f == 3.14
Parses all of string; raises exception if any of it is invalid. ruby-doc.org
s = "3.14" f = Float(s) # f == 3.14