The parseInt() method can be used to convert a string to an integer. For example:
let str = "10"; let num = parseInt(str); console.log(num); // Output: 10
The parseFloat() method can be used to convert a string to a floating-point number. For example:
let str = "3.14"; let num = parseFloat(str); console.log(num); // Output: 3.14
The Number() method can also be used to convert a string to a number. For example:
let str = "5"; let num = Number(str); console.log(num); // Output: 5
let num1 = 5; let num2 = 10; let sum = num1 + num2; console.log(sum); // Output: 15
let num1 = 10; let num2 = 3; let remainder = num1 % num2; console.log(remainder); // Output:
let num1 = 5; let num2 = 10; console.log(num1 < num2); // Output: true
console.log(0.1 + 0.2);
To avoid issues with floating-point precision, it is often recommended to use a library that can handle arbitrary-precision arithmetic, such as the BigNumber.js library.
console.log("5" + 5); // Output: "55" console.log("5" - 2); // Output: 3
In the first example, the string "5" is concatenated with the number 5, resulting in the string "55". In the second example, the string "5" is converted to a number and then subtracted by 2, resulting in the number 3.
To avoid issues with type coercion, it is recommended to always explicitly convert data types before performing operations on them.
From simple addition and subtraction to complex mathematical calculations, numbers are used in a wide range of real-life situations and applications. For example, e-commerce websites use numbers to calculate prices and taxes, social media platforms use numbers to track user engagement and analytics, and scientific research often involves complex calculations that rely on numbers.
Related Tutorials to watch
Top Articles toRead