Codectionary / Developer documentation / JavaScript

Number Methods & Parsing

Number methods handle formatting and validation. toFixed() formats a number to a fixed number of decimal places, returning a string. parseInt() and parseFloat() convert strings to numbers, stopping at the first invalid character. Number.isInteger() and Number.isNaN() provide more reliable type checks than their global counterparts.

Syntax

num.toFixed(digits)
parseInt(string)
parseFloat(string)

Examples

Formatting with toFixed()

Rounding and formatting numbers to a fixed decimal precision.

const price = 19.9899;

console.log(price.toFixed(2)); // "19.99" - returns a STRING
console.log(price.toFixed(0)); // "20"

const whole = 5;
console.log(whole.toFixed(2)); // "5.00"

parseInt() and parseFloat()

Extracting numeric values from the start of a string.

console.log(parseInt("42px"));     // 42 - stops at the first non-numeric character
console.log(parseInt("3.14"));     // 3 - parseInt ignores decimals
console.log(parseFloat("3.14px")); // 3.14
console.log(parseInt("abc"));      // NaN

// Always specify the radix for parseInt to avoid ambiguity
console.log(parseInt("08", 10)); // 8

Number.isInteger() and Number.isNaN()

More reliable checks than the global isNaN() and manual integer testing.

console.log(Number.isInteger(5));    // true
console.log(Number.isInteger(5.5));  // false

console.log(Number.isNaN(NaN));      // true
console.log(Number.isNaN("hello"));  // false - unlike global isNaN(), does not coerce first
console.log(isNaN("hello"));         // true - global isNaN coerces "hello" to NaN first, which is misleading

Best practices

  • Always specify the radix (base) as the second argument to parseInt(), like parseInt(str, 10), to avoid ambiguity with leading zeros
  • Remember toFixed() returns a string, not a number - convert back with Number() if further math is needed
  • Prefer Number.isNaN() over the global isNaN(), since the global version coerces its argument first and can give misleading results
  • Use Number.isInteger() rather than % 1 === 0 checks for clearer, more explicit integer validation

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation