SyntaxStudy
Sign Up
JavaScript Number Methods: toFixed, parseInt, parseFloat, Number
JavaScript Beginner 7 min read

Number Methods: toFixed, parseInt, parseFloat, Number

Number Conversion and Formatting Methods

Working with numbers in real applications almost always involves converting between strings and numbers, or formatting a number for display. JavaScript provides both instance methods on number values and static functions to handle these conversions.

toFixed(digits)

Called on a number value, toFixed(n) returns a string representation rounded to n decimal places. It is the standard way to display currency or measurements. Note that it returns a string, not a number.

parseInt and parseFloat

parseInt(string, radix) parses a string and returns an integer. Always supply the radix (base) argument — omitting it can cause parseInt to mis-detect octal or hexadecimal prefixes in older environments. parseFloat parses a floating-point number from a string, stopping at the first character it cannot convert.

Number()

The Number() function converts any value to a number. Unlike parseInt, it does not tolerate trailing non-numeric characters — Number('42px') returns NaN while parseInt('42px') returns 42.

Example
const pi = 3.14159;
console.log(pi.toFixed(2));       // '3.14'
console.log(pi.toFixed(0));       // '3'
console.log(parseInt('42px', 10)); // 42
console.log(parseInt('0xFF', 16)); // 255
console.log(parseFloat('3.14abc')); // 3.14
console.log(Number('42'));         // 42
console.log(Number('42px'));       // NaN
console.log(Number(true));         // 1
console.log(Number(false));        // 0
console.log(Number(null));         // 0
console.log(Number(undefined));    // NaN
Pro Tip

When parsing user input that must be a whole number, use parseInt(value, 10) — always pass 10 as the radix to guarantee decimal parsing regardless of the input format.