Floating Point Numbers in JavaScript

By: Dusty Arlia
Published on Wednesday, May 15, 2013, 10:33 AM
Last Updated on Wednesday, July 08, 2015 at 10:53 PM
Total Updates: 4

In JavaScript, all numbers fall under the number data type. You can have numbers in strings, but they will not be handled like numbers. Numbers with decimal points are referred to as floating point numbers, but they will have the number data type.

The most popular encoding format for representing real numbers in a computer readable format is called floating point representation. The rules that guide the formating of these numbers are written in the IEEE Floating-Point Standard.

Since computers read only 1's and 0's at the lowest level (the circuit boards), computers need a way to represent numbers in a binary format (1's and 0's). Floating point representation is a way to do this. Floating point representation adapts scientific notation to represent numbers in binary.

Here is an example of the number 150,000 in scientific notation:

1.5 x 105

While keeping the same form, floating point takes scientic notation and translates it to a binary form:

s × 10e

*s = significand
*e = exponent

In the example above, s is the binary equivalent to the significand and e is the binary equivalent of the exponent. s can be a binary integer, fraction, or mixed number and e can be any binary integer.

To get that original scientific notation number into one long string of binary numbers, a certain format is required. The final binary number will have a single bit represent the sign of the number, a set number of bits to determine the significand, and a set number of bits to represent the exponent. The final result is one long string of 1's and 0's (a binary number).

Here is an example of how the JavaScript interpreter interprets numbers:

//remember to not use quotes
//when initializing your numbers
//quotes are for string values
var x = 5;
var y = 5.0;
if (x === y) {
    document.write("x and y have the same value");

This example prints x and y have the same value to the screen.

Here is another example:

var x = 5;
var y = 5.1;
if (x === y) {
    document.write("x and y have the same value");
else {
    document.write("x and y do NOT have the same value");

In this example, x and y do NOT have the same value gets printed to the screen.

The IEEE-754 floating point representation used by JavaScript (and most other programming langauages) is a binary representation. It can represent the fractions 1/2, 1/8, and 1/1024 exactly, but cannot represent 1/10 (.1) or 1/100 (.01) exactly. JavaScript can represent .1 fairly closely, but the problem comes with testing for equality:

var x = .2 - .1;
var y = .3 - .2;
x == y;             //false
x == .1;            //true
y == .1;            //false

When using JavaScript for financial transactions, use integer cents.