JavaScript Number Methods



JavaScript Number Methods

  • These number methods can be used on all JavaScript numbers.
Method Description
toString() Returns a number as a string
toExponential() Returns a number written in exponential notation
toFixed() Returns a number written with a number of decimals
toPrecision() Returns a number written with a specified length
ValueOf() Returns a number as a number

The toString() Method

  • The toString() method returns a number as a string.
  • All number methods can be used on any type of numbers (literals, variables, or expressions)
javascript-number-methods

Sample Code

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Number Methods</h2>

<p>The toString() method converts a number to a string.</p>

<p id="demo"></p>

<script>
let x = 54321;
document.getElementById("demo").innerHTML =
  x.toString() + "<br>" +
   (54321).toString() + "<br>" +
   (54300 + 21).toString();
</script>

</body>
</html>

Output

JavaScript Number Methods
The toString() method converts a number to a string.
54321
54321
54321

The toExponential() Method

  • toExponential() returns a string, with a number rounded and written using exponential notation.
  • A parameter defines the number of characters behind the decimal point.
javascript-number-precision

Sample Code

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Number Methods</h2>

<p>The toPrecision() method returns a string, with a number written with a specified length:</p>

<p id="demo"></p>

<script>
let x = 9.656;
document.getElementById("demo").innerHTML = 
  x.toPrecision() + "<br>" +
  x.toPrecision(2) + "<br>" +
  x.toPrecision(4) + "<br>" +
  x.toPrecision(6);  
</script>

</body>
</html>

Output

JavaScript Number Methods
The toPrecision() method returns a string, with a number written with a specified length:
9.656
9.7
9.656
9.65600

Related Searches to JavaScript Number Methods