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.

Frequently asked questions

How does JavaScript handle string to number?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Type Coercion" snippet in JavaScript uses `implicit: value + "" | +value | !!value`.
Which code does the JavaScript example use?
The "Type Coercion" snippet uses `implicit: value + "" | +value | !!value`, from the Data Types section of the JavaScript cheat sheet.
Which stacks cover "string to number" on this page?
JavaScript, Python. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Type Coercion": The + operator with a string always coerces to string. Prefer explicit conversion (Number(), String()) to avoid surprises.