String to number

3 snippets across 2 stacks — JavaScript, Python

JSJavaScript

Type Coercion

JS · Data Types
syntax
implicit: value + "" | +value | !!value
explicit: String(v) | Number(v) | Boolean(v)
example
console.log("5" + 3);    // "53" (string concat)
console.log("5" - 3);    // 2   (numeric)
console.log(+"42");       // 42  (to number)
console.log(!!"hello");   // true (to boolean)
console.log(Number(""));  // 0
console.log(Number("ab")); // NaN

Note The + operator with a string always coerces to string. Prefer explicit conversion (Number(), String()) to avoid surprises.

Parsing Numbers

JS · Numbers & Math
syntax
Number(value)
parseInt(string, radix)
parseFloat(string)
example
console.log(Number("42"));        // 42
console.log(Number("3.14abc"));   // NaN
console.log(parseInt("3.14abc")); // 3
console.log(parseFloat("3.14abc")); // 3.14
console.log(parseInt("ff", 16));  // 255

Note Number() is stricter -- rejects partially numeric strings. parseInt() stops at the first non-numeric character. Always pass the radix to parseInt() to avoid octal surprises.

PYPython

Numeric Type Conversion

PY · Numbers
syntax
int(x)
float(x)
complex(real, imag)
example
print(int("42"))
print(int(9.99))
print(float("3.14"))
print(int("0xff", 16))
output
42
9
3.14
255

Note int() truncates toward zero (not floor). int('3.14') raises ValueError; convert to float first, then to int.