Number in JavaScript
In this tutorial, we will learn how to work with numbers in JavaScript using the Number object.
In JavaScript, the Number object is used to work with numbers. It provides methods for converting strings to numbers, formatting numbers, and performing mathematical operations.
Converting Strings to Numbers
The Number object provides methods for converting strings to numbers. You can use the Number() constructor or the parseInt() and parseFloat() functions to convert strings to numbers. Here are some examples:
Number()
The Number() constructor converts a string to a number. If the string contains a valid number, it will be converted to a number; otherwise, it will return NaN (Not-a-Number).
let str = "42";
console.log(Number(str)); // 42parseInt()
The parseInt() function parses a string and returns an integer. It takes an optional second argument to specify the radix (base) of the number. If the string does not start with a valid number, it will return NaN.
let str = "42px";
console.log(parseInt(str)); // 42parseFloat()
The parseFloat() function parses a string and returns a floating-point number. It ignores leading whitespace and stops parsing when it encounters an invalid character.
let str = "3.14";
console.log(parseFloat(str)); // 3.14Formatting Numbers
The Number object provides methods for formatting numbers. You can use the toFixed(), toPrecision(), and toExponential() methods to format numbers in different ways. Here are some examples:
toFixed()
The toFixed() method formats a number using fixed-point notation with a specified number of decimal places.
let num = 3.14159;
console.log(num.toFixed(2)); // 3.14toPrecision()
The toPrecision() method formats a number to a specified length, including the integer part and the decimal part.
let num = 123.456;
console.log(num.toPrecision(4)); // 123.5toExponential()
The toExponential() method formats a number using exponential notation with a specified number of digits.
let num = 123456;
console.log(num.toExponential(2)); // 1.23e+5Experimenting with Numbers
You can experiment with numbers in JavaScript. Here are some examples:
console.log(Number(true)); // 1
console.log(Number(false)); // 0
console.log(Number("42")); // 42You can also use the isNaN() function to check if a value is NaN:
console.log(isNaN(Number("xyz"))); // trueConclusion
- The
Numberobject is used to work with numbers in JavaScript. - You can convert strings to numbers using the
Number()constructor,parseInt(), andparseFloat()functions. - You can format numbers using the
toFixed(),toPrecision(), andtoExponential()methods. - You can experiment with numbers and check if a value is
NaNusing theisNaN()function.
How is this guide?
Sign in to share your feedback
Help us improve by sharing your thoughts on this guide.
Last updated on