JavaScript Number Methods
Number methods help you work with numeric data more effectively. Converting strings to numbers, fixing decimal places, and verifying if values are finite or not are common tasks these methods simplify.
Key Topics
- parseInt() and parseFloat()
- toString() and toFixed()
- isFinite() and isNaN()
- JavaScript Usage in DOM
- Key Takeaways
parseInt() and parseFloat()
parseInt()
converts a string to an integer, while parseFloat()
handles decimals as well.
console.log(parseInt("42"));
console.log(parseFloat("3.14"));
Output
> 42
> 3.14
Explanation: "42"
becomes 42
(integer) and "3.14"
becomes 3.14
(float) after parsing.
toString() and toFixed()
toString()
converts a number to a string, while toFixed()
rounds a number to a specified number of decimal places.
let num = 5.6789;
console.log(num.toString());
console.log(num.toFixed(2));
Output
> "5.6789"
> "5.68"
Explanation: toString()
returns a string representation of the number, and toFixed(2)
rounds it to two decimal places.
isFinite() and isNaN()
isFinite()
checks if a value is a finite number, and isNaN()
checks if a value is NaN
(Not a Number).
console.log(isFinite(42));
console.log(isNaN("Hello"));
Output
> true
> true
Explanation: 42
is a finite number, so isFinite(42)
returns true
. The string "Hello" is not a number, so isNaN("Hello")
returns true
.
JavaScript Usage in DOM
This DOM-based example demonstrates converting user input into numbers and formatting them before displaying on the page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number Methods in DOM</title>
</head>
<body>
<h1>Number Methods Demo</h1>
<input type="text" id="numInput" placeholder="Enter a number">
<button onclick="formatNumber()">Format</button>
<p id="output"></p>
<script>
function formatNumber() {
let inputVal = document.getElementById("numInput").value;
let parsed = parseFloat(inputVal);
if (isNaN(parsed)) {
document.getElementById("output").textContent = "Please enter a valid number.";
} else {
document.getElementById("output").textContent = "Formatted: " + parsed.toFixed(2);
}
}
</script>
</body>
</html>
Key Takeaways
- Parsing: Use
parseInt()
andparseFloat()
to convert strings to numbers. - Formatting:
toString()
andtoFixed()
create readable numeric outputs. - Validation:
isFinite()
andisNaN()
help ensure correct numeric input. - DOM Integration: Process and display numeric values interactively on webpages.