JavaScript Tutorial – Number

JavaScript numbers can be written with, or without decimals.

<script type="text/javascript">
   var x = 1.23;
   var y = 1;
</script>

JavaScript Number is Always 64-bit Floating Point

This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63

Precision

Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits.

Infinity

Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number. Division by 0 (zero) also generates Infinity

NaN – Not a Number

NaN is a JavaScript reserved word indicating that a value is not a number.

NaN Example

<script type="text/javascript">
   var x = 1 / "JS";  // x will be NaN
</script>

By default, JavaScript numbers are base 10. You can use toString() to output number in different bases.

Output number as base 16 (hex)

JavaScript number to base 16 (hex)

<script type="text/javascript">
   var num = 256;
   num.toString(16);  // returns 100
</script>
Try it yourself »

Output number as base 8 (octal)

JavaScript number to base 8 (octal)

<script type="text/javascript">
   var num = 256;
   num.toString(8);  // returns 400
</script>
Try it yourself »

Output number as base 2 (binary)

JavaScript number to base base 2 (binary)

<script type="text/javascript">
   var num = 256;
   num.toString(2);  // returns 100000000
</script>
Try it yourself »