JavaScript Number Methods
Number methods let you format, convert, and validate numeric values in JavaScript.
JavaScript Number Methods
JavaScript provides methods that turn numbers into formatted strings, and global or Number functions that convert strings back into numbers. Some methods belong to individual number values, while others live on the Number object itself and are called directly.
The formatting methods return strings, which is important to remember: once you call toFixed() or toString(), you can no longer do arithmetic on the result without converting it back.
Formatting numbers as strings
<!DOCTYPE html>
<html>
<body>
<h2>Formatting numbers as strings</h2>
<script>
let price = 9.5;
console.log(price.toFixed(2)); // "9.50" (2 decimal places)
console.log((1000).toString()); // "1000"
console.log((255).toString(16)); // "ff" (base 16 / hex)
let pi = 3.14159;
console.log(pi.toPrecision(3)); // "3.14" (3 significant digits)
</script>
</body>
</html>To convert text into a number, use Number(), parseInt(), or parseFloat(). Number() is strict and returns NaN for anything that is not a clean number, while parseInt() and parseFloat() read as many valid digits as they can from the start of the string and ignore the rest.
Converting strings to numbers
<!DOCTYPE html>
<html>
<body>
<h2>Converting strings to numbers</h2>
<script>
console.log(Number("42")); // 42
console.log(Number("42px")); // NaN (strict)
console.log(parseInt("42px")); // 42 (reads leading digits)
console.log(parseFloat("3.14m")); // 3.14
console.log(parseInt("ff", 16)); // 255 (parse as hex)
</script>
</body>
</html>- Number.isInteger(value) — true only for whole numbers.
- Number.isNaN(value) — the reliable way to test for NaN.
- Number.isFinite(value) — true when the value is a real, finite number.
- toFixed(n) — rounds to n decimal places and returns a string.
Validating numbers
<!DOCTYPE html>
<html>
<body>
<h2>Validating numbers</h2>
<script>
console.log(Number.isInteger(10)); // true
console.log(Number.isInteger(10.5)); // false
console.log(Number.isFinite(1 / 0)); // false (Infinity)
console.log(Number.isNaN(Number("x"))); // true
// toFixed rounds, and returns a string
console.log((2.567).toFixed(1)); // "2.6"
</script>
</body>
</html>