Number Parsing in JavaScript

Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in JavaScript.

// JavaScript doesn't have a built-in package for number parsing like Go's strconv,
// but it provides global functions and methods for parsing numbers.

// With parseFloat, we can parse floating-point numbers
let f = parseFloat("1.234");
console.log(f);

// parseInt is used for parsing integers. The second argument specifies the radix (base).
// 10 is used for decimal, 16 for hexadecimal, etc.
let i = parseInt("123", 10);
console.log(i);

// parseInt will recognize hex-formatted numbers when the radix is 16 or 0
let d = parseInt("0x1c8", 16);
console.log(d);

// JavaScript doesn't have a separate function for parsing unsigned integers.
// parseInt is used for both signed and unsigned integers.
let u = parseInt("789", 10);
console.log(u);

// JavaScript doesn't have a direct equivalent to Go's Atoi function.
// parseInt with base 10 can be used for basic base-10 int parsing.
let k = parseInt("135", 10);
console.log(k);

// Parse functions return NaN (Not-a-Number) on bad input.
let e = parseInt("wat", 10);
console.log(e);

To run this JavaScript code, you can save it in a file (e.g., number-parsing.js) and run it using Node.js:

$ node number-parsing.js
1.234
123
456
789
135
NaN

JavaScript’s number parsing functions behave slightly differently from Go’s:

  1. There’s no need to specify bit precision as JavaScript uses double-precision floating-point format for all numbers.
  2. parseInt and parseFloat are global functions, not methods of a specific object.
  3. JavaScript doesn’t distinguish between signed and unsigned integers at the language level.
  4. Error handling is different: instead of returning an error, JavaScript’s parsing functions return NaN for invalid input.

Next, we’ll look at another common parsing task: URLs.