freeCodeCamp/guide/english/javascript/numbers/index.md

2.7 KiB

title
Numbers

Numbers

The implementation of JavaScript's numbers is based on the IEEE 754 standard, often called "floating-point."

IEEE 754 Wikipedia Link
IEEE 754 Double Precision Floating Point Visualization

Number literals are expressed generally as base-10 decimal literals.

var foo = 47;
var bar = 47.9;

The leading portion of a decimal value, if 0, is optional:

var same = 0.47;
var stillSame = .47;

Similarly, the trailing portion (the fractional) of a decimal value after the ., if 0, is optional:

var a = 47.0;
var b = 47.;

By default, most numbers will be outputted as base-10 decimals, with trailing fractional 0s removed. So:

var foo = 47.300;
var bar = 47.0;

foo; // 47.3
bar; // 47

Very large or very small numbers can be written as:

var foo = 47e8; // 4700000000
var baz = 47e-8; // 00.00000047  

toExponential method can be used to convert a number into its exponential notation.

var foo = 47e8;
foo;  // 4700000000
foo.toExponential()   //"47e8"

Numbers have access to methods that are built into Number.prototype.

For Example: toFixed() method formats a number with a specific number of digits to the right of the decimal.

var foo = 47.69;
foo.toFixed(0);  // "48"
foo.toFixed(1);  // "47.7"
foo.toFixed(2);  // "47.69"

Type Number.prototype in your browser and see other available methods yourself.

Numbers in strings are treated differently than normal numbers.

var foo = "12" + 18; // "1218"

In order to convert a string into a number you must run it through a Number() function.

var foo = "12";
var bar = Number(foo) + 18; // "30"

More Information:

  1. MDN
  2. JavaScript Numbers

References

  1. Types & grammar by Kyle Simpson.
  2. ECMAScript Language Specification: 4.3.20
  3. ECMAScript Language Specification: 15.7 Number Objects