Number Methods and Formatting

Updated · 7 min read
easyES2026javascriptnumbersparseintintlformatting

Number methods are the built-in functions used to convert values to numbers, check them, and turn them back into text for people to read. Data reaches a program as text (form fields, URLs, CSV files), so converting it correctly comes first. Showing results comes last, and Intl.NumberFormat turns 1234.5 into $1,234.50 without any string tricks.

In One Minute

  • Number(text) converts a whole string or returns NaN. parseInt and parseFloat read a number from the start of a string and ignore the rest.
  • Always pass the base to parseInt: parseInt("08", 10).
  • toFixed(2) rounds to 2 decimals and returns a string.
  • Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }) formats dollars; toLocaleString is the shortcut.
  • Number.isInteger, Number.isFinite and Number.isNaN check values without converting them.

Method Table

MethodDescription
Number(value)It is used to convert a value to a number; the whole string must be numeric.
parseInt(text, radix)It is used to read an integer from the start of a string, in base radix.
parseFloat(text)It is used to read a decimal number from the start of a string.
num.toFixed(digits)It is used to round to digits decimals, returning a string.
num.toPrecision(digits)It is used to round to digits significant digits, returning a string.
num.toString(radix)It is used to convert to a string, optionally in another base.
num.toLocaleString(locale, options)It is used to format for people, like Intl.NumberFormat.
Number.isInteger(x)It is used to check for a whole number.
Number.isFinite(x)It is used to check for a real, finite number (no conversion).
Number.isNaN(x)It is used to check for NaN (no conversion).
Number.isSafeInteger(x)It is used to check for an integer in the exact range.

Converting Text to Numbers

convert.js▶ Try it
console.log(Number("120"));
console.log(Number("120.50"));
console.log(Number("  45  "));
console.log(Number("120px"));
console.log(Number(""));
console.log(Number(null), Number(undefined), Number(true));
 
console.log(parseInt("120px", 10));
console.log(parseFloat("45.75 dollars"));
console.log(parseInt("3.99", 10));
console.log(parseInt("abc", 10));
Output
120
120.5
45
NaN
0
0 NaN 1
120
45.75
3
NaN

Explanation:

  • Number is strict: the whole string (ignoring spaces at the ends) must be a number, or the result is NaN. But watch the edge cases: an empty string becomes 0, and so does null.
  • parseInt and parseFloat are forgiving: they read digits from the start and stop at the first character that doesn't fit. parseInt("3.99") stops at the dot and gives 3; it does not round.
InputNumberparseInt(x, 10)parseFloat
"120"120120120
"120.75"120.75120120.75
"120px"NaN120120
""0NaNNaN
"1e3"100011000

Always Give parseInt a Base

parseInt(text, radix) reads the text in base radix (2 to 36). Without it, a string starting with 0x is read as hexadecimal. Passing 10 makes intent clear, and linters require it:

radix.js▶ Try it
console.log(parseInt("0x1f"));
console.log(parseInt("0x1f", 10));
console.log(parseInt("1010", 2));
console.log(parseInt("ff", 16));
Output
31
0
10
255

Rounding for Display: toFixed

toFixed(n) rounds to n decimal places and returns a string:

to-fixed.js▶ Try it
const fee = 120.5;
console.log(fee.toFixed(2));
console.log(typeof fee.toFixed(2));
console.log((0.1 + 0.2).toFixed(2));
console.log((1.005).toFixed(2));
console.log((2.345).toFixed(2));
Output
120.50
string
0.30
1.00
2.35

Explanation: 1.005 is actually stored as 1.00499999999999989..., so it rounds down to 1.00. Rounding of halves follows the stored binary value, not the decimal you typed. For money kept in cents, this never comes up: you only divide by 100 at the very end.

Formatting for People: Intl.NumberFormat

Intl.NumberFormat is the built-in formatter for numbers in any language and region. It handles thousands separators, currency symbols, percentages and compact forms:

intl.js▶ Try it
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
console.log(usd.format(1234.5));
console.log(usd.format(0.1 + 0.2));
console.log(usd.format(-45));
 
const whole = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", maximumFractionDigits: 0 });
console.log(whole.format(1350));
 
console.log(new Intl.NumberFormat("en-US").format(1234567.891));
console.log(new Intl.NumberFormat("en-US", { style: "percent" }).format(0.075));
console.log(new Intl.NumberFormat("en-US", { notation: "compact" }).format(2500000));
console.log((1234.5).toLocaleString("en-US", { style: "currency", currency: "USD" }));
Output
$1,234.50
$0.30
-$45.00
$1,350
1,234,567.891
8%
2.5M
$1,234.50
OptionExampleEffect
style: "currency", currency: "USD"$1,234.50Money
style: "percent"8%Multiplies by 100
minimumFractionDigits, maximumFractionDigits7.50%Control decimals
notation: "compact"2.5MShort large numbers
signDisplay: "always"+45Show the plus sign

Create a formatter once and reuse it: building one is slower than calling format. num.toLocaleString(locale, options) does the same thing in one call and is fine for occasional use.

Bases and Other Conversions

toString(radix) converts a number to a string in another base, the reverse of parseInt:

to-string.js▶ Try it
console.log((255).toString(16));
console.log((10).toString(2));
console.log((120).toString());
console.log(String(120) === (120).toString());
console.log((1234.5678).toPrecision(6));
Output
ff
1010
120
true
1234.57

Note the parentheses around (255): in 255.toString(), the parser reads 255. as a decimal number and then fails at toString.

In Practice

The Fee Tracker reads an amount field, validates it strictly, and shows a confirmation with US formatting:

amount-field.js▶ Try it
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
 
function parseAmount(field) {
  const text = field.trim().replace(/^\$/, "").replaceAll(",", "");
  if (text === "") return { error: "Enter an amount." };
  const amount = Number(text);
  if (!Number.isFinite(amount)) return { error: `"${field}" is not a number.` };
  if (amount <= 0) return { error: "The amount must be more than zero." };
  return { cents: Math.round(amount * 100) };
}
 
for (const field of ["$1,234.50", "120", "", "12abc", "-5"]) {
  const result = parseAmount(field);
  console.log(result.error ?? `Recorded ${usd.format(result.cents / 100)}`);
}
Output
Recorded $1,234.50
Recorded $120.00
Enter an amount.
"12abc" is not a number.
The amount must be more than zero.

Common Mistakes

Using parseInt to validate input. parseInt("12abc", 10) is 12. Use Number and check for NaN.

Treating Number("") as invalid. It is 0. Check for empty strings first.

Doing math with toFixed results. They are strings. Format last.

Building currency strings by hand. "$" + amount.toFixed(2) has no thousands separator and puts the minus sign in the wrong place for negatives. Use Intl.NumberFormat.

Practice

Challenge: Write formatReport(totals) that takes an object of grade totals in cents and prints each as Grade 9: $1,234.50, followed by the grand total.

Show solution
report.js▶ Try it
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
 
function formatReport(totals) {
  let grand = 0;
  for (const [grade, cents] of Object.entries(totals)) {
    console.log(`Grade ${grade}: ${usd.format(cents / 100)}`);
    grand += cents;
  }
  console.log(`Total: ${usd.format(grand / 100)}`);
}
 
formatReport({ 9: 123450, 10: 98000, 11: 4500 });
Output
Grade 9: $1,234.50
Grade 10: $980.00
Grade 11: $45.00
Total: $2,259.50

Quick check: Number methods

3 questions
1What does Number("120px") return?
2What type does (12.5).toFixed(2) return?
3Which formats 1234.5 as $1,234.50?

Key Takeaways

TaskCode
Validate a number fieldNumber(text) then Number.isFinite
Pull a number from textparseFloat("45.5kg")
Two decimalsx.toFixed(2)
Dollarsnew Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })
Percent{ style: "percent" }

Was this tutorial helpful?

Lesson 24 of 139