JavaScript provides several built-in methods to work with numbers efficiently. These methods allow you to convert, format, round, and manipulate numbers as needed in different scenarios. Understanding these methods helps in handling numeric data effectively in JavaScript applications.
JavaScript allows numbers to be converted into strings, which can be useful for displaying data in user interfaces.
toString()
– Converts a Number to a Stringlet num = 100;
console.log(num.toString()); // "100"
console.log((123).toString()); // "123"
📌 This is useful when you need to store numbers as text, such as in HTML or databases.
Sometimes, numbers need to be formatted to a fixed decimal place or rounded for display purposes.
toFixed()
– Rounds and Sets Decimal PlacesThis method rounds the number and ensures it has a specified number of decimal places.
let num = 3.14159;
console.log(num.toFixed(2)); // "3.14"
console.log(num.toFixed(0)); // "3"
📌 Commonly used for formatting prices, percentages, and other decimal-based values.
toPrecision()
– Sets the Total Number of DigitsUnlike toFixed()
, this method controls the total number of significant digits.
let num = 123.456;
console.log(num.toPrecision(4)); // "123.5"
console.log(num.toPrecision(2)); // "1.2e+2"
📌 Useful when working with scientific data or limiting the number of digits shown.
JavaScript allows the conversion of different data types (like strings) into numbers using various methods.
Number()
– Converts a Value to a Numberconsole.log(Number("123")); // 123
console.log(Number("12.34")); // 12.34
console.log(Number("abc")); // NaN
📌 If the conversion fails, it returns NaN (Not a Number).
parseInt()
– Converts a String to an IntegerThis method extracts the whole number from a string and ignores non-numeric characters.
console.log(parseInt("100px")); // 100
console.log(parseInt("12.75")); // 12
📌 Useful for extracting numbers from mixed data like "50px"
in CSS.
parseFloat()
– Converts a String to a FloatUnlike parseInt()
, this method keeps decimal values.
console.log(parseFloat("10.5px")); // 10.5
console.log(parseFloat("99")); // 99
📌 Used when dealing with floating-point values in calculations.
JavaScript offers powerful number methods that help in converting, formatting, and validating numeric data. These methods play an essential role in web development, especially when handling prices, user input, and mathematical operations.
@asadmukhtar