We must have had various scenarios to convert a number. For example, the data fetched from an API or a database query in a string format to a number. As strings are operated upon differently, it may be necessary to convert these strings to a number format to perform arithmetic operations on them with ease. Here are a few ways to do so:
Number() is a function of the
Number construct which can be used to convert other data types to a number format (as per the MDN Docs). It returns
NaN if the input parameter is either undefined or not convertible to a number. Hence, it just serves our purpose to convert a string to a number. For instance:
console.log(Number("246")) console.log(Number("246.5")) console.log(Number(undefined)) console.log(Number("Hello"))
246 246.5 NaN NaN
Another way of dealing with string numbers is using the
parseInt() takes two arguments, one is the string that needs to be converted, and the other one is the radix (means the base). Most numbers that we deal with in our day-to-day life are usually in the base of 10, which signifies a decimal value. In most cases, we don’t need to specify the radix as the default is 10.
console.log(parseInt("123")); console.log(parseInt("abc")); console.log(parseInt("-123")); console.log(parseInt("100.50"));
123 NaN -123 100
parseInt("100.50") returns 100 instead of 100.50, as it converts the input number to a floating [point number. Hence, while using
parseInt() be aware of the fact.
parseInt() also can convert hexadecimal values and values with the different base number systems, like the binary system, the octal system, etc. For more information, check out the docs. Similarly, we can use
parseFloat() to convert a string to a floating-point number.
console.log(Math.ceil("123")); console.log(Math.floor("300")); console.log(Math.abs("450"));
123 300 450
However, there is a pitfall when using the
Math methods for conversion. For floating-point values, we cannot use them as they will convert those into an integer. Hence, we will lose the decimal part of the value.
221as supposed to
220.5. It takes the ceiling value, approximating the decimal number to the next integer value that is
221. Hence, we cannot use it to get
220.5. In such scenarios use
220. As compared to
floor()returns the previous integer value. Hence
Math.floor()would not work for floating point number values.
Math.abs("450"): Can be used as it will return
450but would not work out with negative integer values. For instance, the following difference will not serve our purpose when dealing with negative integer values. As per the following scenarios:
240.64 // The decimal value of .64 is captured here 240.25 // -240.25 is transformed to 240.25
Depending upon the value that we expect out of the string number, the best option will be to use the
Number() method. If you are playing with only integer values, we recommend using the