
Java Programming - Beginner to Advanced.Data Structure & Algorithm-Self Paced(C++/JAVA).Data Structures & Algorithms in JavaScript.Data Structure & Algorithm Classes (Live).ES6 in Action: New String Methods - String.prototype.25+ JavaScript Shorthand Coding Techniques.
#Js convert string to number how to#

NaN is a global property that represents Not-a-Number. When using Number(), if the string contains characters other than numbers, plus(+) and minus(-) signs at the beginning, or decimal points, the returned value is the special value NaN (Not-a-Number). It’s important to take into account cases where a string might contain characters other than numbers and how each approach handles this. How to Handle Non-Numeric Characters in Strings To avoid any confusion, always specify the base when using parseInt(). So, for example, if you were to call parseInt("08"), the input value would be considered an octal number but 8 is not an octal digit (because octal numbering is 0–7), so the function would return a value of zero, not eight. A number beginning 0x or 0X is considered to be hexadecimal (base 16), and all other numbers are considered to be decimal. That is, it detects the base of a number by its format in the string. Without this second argument, parseInt performs automatic radix detection. This argument is in fact optional, but it’s highly recommend that you always provide it. ParseInt() takes a second argument that specifies the base of the number to be parsed from the string. You can see the example in action in the following CodePen demo.Ĭonvert String to Number with parseInt() and parseFloat() by SitePoint ( CodePen. On the other hand, when parsing str using parseFloat, the value of floatNumber becomes 10.1 as a number and its type is number. However, when parsing str using parseInt, the value of intNumber becomes 10 and its type is number. Similar to the first approach, when logging the value of str and its type in the console, the result is 10.1 as a string and string respectively. log ( typeof intNumber ) // "number" const floatNumber = parseFloat (str ) console.

log ( typeof str ) // "string" const intNumber = parseInt (str ) console. As you can tell, parseInt() parses a string to an integer, whereas parseFloat() parses a string to a number with decimal points.įor example: const str = "10.9" console.

Convert a String to a Number Using parseInt() and parseFloat()Īnother approach is using parseInt() and parseFloat().
