Javascript

[JavaScript] JavaScript / Functions / Number() / Function that converts a string to a number

OOQ 2022. 8. 5. 10:19
728x90
SMALL

#JavaScript

#JavaScript / Functions / Number() / Function that converts a string to a number

Number()

Number() is a function that converts a string to a number.

Grammar

Number( object )
  • object: Enter a string or a variable whose value is a string.
  • Returns NaN for values ​​that cannot be converted to a number.

example

  • The value of variable c is 12, which is character 1 plus character 2.
  • The value of variable d is 3, which is the addition of number 1 and number 2.
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>JavaScript</title>
    <style>
      body {
        font-family: Consolas;
      }
    </style>
  </head>
  <body>
    <script>
      var a = '1';
      var b = '2';
      var c = a + b;
      var d = Number( a ) + Number( b );
      document.write( '<h1>c : ' + c + '</h1>' );
      document.write( '<h1>d : ' + d + '</h1>' );
    </script>
  </body>
</html>

TIP.
Use the String() function to convert numbers to strings.

728x90
LIST