Skip to content

JavaScript string as number | parseint, number function

  • by

Type decoration are not needed like in Javascript variables like int, Stings, etc. It auto get type by variable value. String is define single( ‘ ‘ ) or double (” “) quote. JavaScript string as the number is nothing just you can define numbers value only inside the quotes then it will become strings.

Define JavaScript string as a number

Let’s define a number in double quote as a string. And then check if its string or not?

<!DOCTYPE html>
<html>
  <head>
    <script>

    	var str_num1 = "10";
    	var str_num2 = '20';
		
		alert(typeof str_num1 === 'string')

    </script>
  </head>   

</html>

Output:

JavaScript string as number

How to change string as number to Number

As we learned about JS string as number now let’s convert it into number(int/integer) type data.

We are doing examples with parseint() and Number() Function.

After converted will check its number or not using Number.isInteger() method.

1. JavaScript parseInt() Function

The parseInt() function parses a string and returns an integer.

<!DOCTYPE html>
<html>
  <head>
    <script>

    	var str_num1 = "10";
    	var a = parseInt(str_num1)
		
		alert(Number.isInteger(a))

    </script>
  </head>   

</html>

Output: true

2. JavaScript Number() Function

Convert different object values to their numbers:

Number('123')  // returns the number 123
Number('123') === 123  // true

Number("unicorn")  // NaN
Number(undefined)  // NaN

Do comment if you have any doubts and suggestion on this tutorial.

Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *