JavaScript provides built-in methods on the Number object and prototype for parsing strings into numbers, formatting numeric output, and validating integer boundaries.
flowchart TD
NumberUtils["Number Utilities"] --> Parsing["Parsing: parseInt(), parseFloat()"]
NumberUtils --> Formatting["Formatting: toFixed(), toPrecision(), toString()"]
NumberUtils --> Validation["Validation: Number.isInteger(), Number.isFinite()"]
| Method | Input | Return | Description |
|---|---|---|---|
toFixed(digits) |
Number | String | Formats number with fixed decimal digits ((10.567).toFixed(2) -> "10.57"). |
parseInt(str, radix) |
String, Radix | Number / NaN | Parses string into integer using specified base (e.g. radix 10 or 16). |
parseFloat(str) |
String | Number / NaN | Parses string into floating point number. |
Number.isInteger(val) |
Any | Boolean | Returns true if value is a finite integer. |
Number.isFinite(val) |
Any | Boolean | Returns true if value is a finite number (excludes NaN, Infinity). |
// Demonstrating Number parsing, formatting, and validation methods
// 1. Formatting Numbers for UI Display
const rawPrice = 1299.9482;
console.log(`Fixed 2 decimals: $${rawPrice.toFixed(2)}`); // "$1299.95"
console.log(`Precision (4 digits): ${rawPrice.toPrecision(4)}`); // "1300"
// 2. String Parsing with parseInt and parseFloat
const pxString = "120px";
const parsedInt = parseInt(pxString, 10); // Always specify radix 10!
console.log(`Parsed Int from '120px': ${parsedInt}`); // 120
const floatString = "99.95 USD";
const parsedFloat = parseFloat(floatString);
console.log(`Parsed Float: ${parsedFloat}`); // 99.95
// 3. Internationalized Currency Formatting (Intl.NumberFormat)
const currencyFormatter = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD"
});
console.log(`Formatted USD: ${currencyFormatter.format(rawPrice)}`); // "$1,299.95"
// 4. Number Validation Checks
console.log(`Number.isInteger(42): ${Number.isInteger(42)}`); // true
console.log(`Number.isInteger(42.5): ${Number.isInteger(42.5)}`); // false
parseInt(): Always pass 10 as the second parameter (parseInt(str, 10)) to avoid unintended octal or hex parsing.toFixed() Returns a String: Remember that toFixed() returns a string, not a number. Wrap in Number() if further math operations are needed.Number.isFinite(): Use Number.isFinite() over global isFinite() to avoid implicit type coercion.Parse the hex string "FF" into a base-10 decimal integer using parseInt().
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.