Number Methods and Formatting
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 returnsNaN.parseIntandparseFloatread 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;toLocaleStringis the shortcut.Number.isInteger,Number.isFiniteandNumber.isNaNcheck values without converting them.
Method Table
| Method | Description |
|---|---|
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
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));120
120.5
45
NaN
0
0 NaN 1
120
45.75
3
NaNExplanation:
Numberis strict: the whole string (ignoring spaces at the ends) must be a number, or the result isNaN. But watch the edge cases: an empty string becomes0, and so doesnull.parseIntandparseFloatare 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 gives3; it does not round.
| Input | Number | parseInt(x, 10) | parseFloat |
|---|---|---|---|
"120" | 120 | 120 | 120 |
"120.75" | 120.75 | 120 | 120.75 |
"120px" | NaN | 120 | 120 |
"" | 0 | NaN | NaN |
"1e3" | 1000 | 1 | 1000 |
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:
console.log(parseInt("0x1f"));
console.log(parseInt("0x1f", 10));
console.log(parseInt("1010", 2));
console.log(parseInt("ff", 16));31
0
10
255Rounding for Display: toFixed
toFixed(n) rounds to n decimal places and returns a string:
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));120.50
string
0.30
1.00
2.35Explanation: 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:
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" }));$1,234.50
$0.30
-$45.00
$1,350
1,234,567.891
8%
2.5M
$1,234.50| Option | Example | Effect |
|---|---|---|
style: "currency", currency: "USD" | $1,234.50 | Money |
style: "percent" | 8% | Multiplies by 100 |
minimumFractionDigits, maximumFractionDigits | 7.50% | Control decimals |
notation: "compact" | 2.5M | Short large numbers |
signDisplay: "always" | +45 | Show 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:
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));ff
1010
120
true
1234.57Note 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:
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)}`);
}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
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 });Grade 9: $1,234.50
Grade 10: $980.00
Grade 11: $45.00
Total: $2,259.50Key Takeaways
| Task | Code |
|---|---|
| Validate a number field | Number(text) then Number.isFinite |
| Pull a number from text | parseFloat("45.5kg") |
| Two decimals | x.toFixed(2) |
| Dollars | new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }) |
| Percent | { style: "percent" } |
Was this tutorial helpful?