JavaScript number methods convert strings into numbers, validate numeric inputs, and format decimals for display. Knowing when to use Number(), Number.parseInt(), and toFixed() prevents silent form-input bugs.
JavaScript gives you dedicated parsing functions on Number along with prototype formatting helpers. Always check the return type, because parsing returns numbers while formatting returns strings:
| Method | Input Example | Return Value | Best Use Case |
|---|---|---|---|
Number(val) |
Number("42.5") |
42.5 (number) |
Strict full-string conversion |
Number.parseInt(str, 10) |
Number.parseInt("24px", 10) |
24 (number) |
Extracting leading integers |
Number.parseFloat(str) |
Number.parseFloat("3.5rem") |
3.5 (number) |
Extracting leading decimals |
num.toFixed(n) |
(9.5).toFixed(2) |
"9.50" (string) |
Formatting decimal places |
Number.isInteger(val) |
Number.isInteger(12) |
true (boolean) |
Checking whole numbers |
Calling Number.parseInt() and Number.parseFloat() is preferred over the older global parseInt() and parseFloat() functions. Both behave identically, yet attaching them to Number keeps the global scope cleaner and signals intent clearly.
Remember that toFixed() returns a string, not a number. For localized currency or comma grouping, Intl.NumberFormat gives clean production formatting.
const rawQuantity = " 15 ";
const rawCssSize = "18.5px";
const qty = Number(rawQuantity); // 15 (returns NaN for "15abc")
const pxValue = Number.parseFloat(rawCssSize); // 18.5
const unitPrice = 29.5;
const formattedPrice = (unitPrice * 1.075).toFixed(2); // "31.71"
const currencyDisplay = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(Number(formattedPrice));
console.log({ qty, pxValue, formattedPrice, currencyDisplay });
toFixed(): Doing price.toFixed(2) + 5 concatenates "10.005" instead of adding 5. Keep numbers numeric until final UI display.parseInt() for strict validation: Number.parseInt("12abc", 10) returns 12 and ignores "abc". Use Number(str) when the entire string must be a valid number.10 in parseInt(): Always pass 10 as the second argument so intent is explicit across all inputs.Number("") or Number(" ") return?Number("") and Number(" ") return 0! Always check str.trim() !== "" before converting optional text inputs into numbers.
Use Math.round((value + Number.EPSILON) * 100) / 100, or wrap Number(value.toFixed(2)) for simple display calculations.
Number.isFinite() and global isFinite()?Number.isFinite("10") returns false without coercing types, while global isFinite("10") converts "10" to 10 and returns true.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.