JavaScript Numbers

Number can be integers (whole numbers, such as 3) or floating point decimals (often referred to as just "decimals" or "floats", such as 3.14159). For example:
typeof 3;
<< "number"


typeof 3.14159;
<< "number"
  


As you can see in the examples above, JavaScript doesn’t distinguish between integers and floating point decimalsthey are both given the type of "number", which is a different approach to most other programming languages. This is set out in the ECMAScript specification, although most JavaScript engines will treat integers and floats differently in the background in order to improve efficiency. 

Number Constructor Function

Just like strings, numbers also have a constructor function:
new Number(3) 

This is much more verbose than simply writing the number 3, which is known as a number literal, so it is recommended that you stick to using number literals.



Octal and Hexadecimal Numbers

If a number starts with a 0x, it is considered to be in hexadecimal (base 16) notation:

0xAF; // A represents 10, F represents 15
<< 175
 

Hexadecimal or "hex" numbers are often used for color codes on the Web. You can read more about them on Wikipedia


Exponential Notation

Numbers can also be represented in exponential notation, which is shorthand for "multiply by 10 to the power of" (you may have heard this referred to as "scientific notation" or "standard form"). Here are some examples:
1e6; // means 1 multiplied by 10 to the power 6 (a million)
<< 1000000

2E3; // can also be written as 2E3, 2E+3 and 2e+3
<< 2000
  

Fractional values can be created by using a negative index value:
2.5e-3; // means 2.5 multiplied by 10 to the power -3 (0.001)
<< 0.0025
 

Number Methods

Numbers also have some built-in methods, although you need to be careful when using the dot notation with number literals that are integers because the dot can be confused for a decimal point. There are a few ways to deal with this, which we’ll demonstrate with the toExponential() method; this returns the number as a string in exponential notation.
Use two dots:
5..toExponential(); >> "5e+0" 

Put a space before the dot:
5 .toExponential(); >> "5e+0" 

Always write integers as a decimal:
5.0.toExponential(); >> "5e+0

Place the integer in parentheses:
(5).toExponential(); >> "5e+0" 

Assign the number to a variable:
var number = 5;
>> 5


number.toExponential();
>> "5e+0"
 

The toFixed() method rounds a number to a fixed number of decimal places:
var pi = 3.1415926;
<< undefined

pi.toFixed(3); // only one dot needed when using variables
<< "3.142"
 

Note that the value is returned as a string.

The
toPrecision() method rounds a number to a fixed number of significant figures that is once again returned as a string (and often using exponential notation):

325678..toPrecision(2);
<< "3.3e+5"

2.459.toPrecision(2);
<< "2.5"
 

Arithmetic Operations

All the usual arithmetic operations can be carried out in JavaScript. 

Addition:
5 + 4.3;
<< 9.3
  

Substraction:
6 - 11;
>> -5
 

Multiplication:
6 * 7;
<< 42
 

Division:
3/7;
<<0.42857142857142855
 

You can also calculate the remainder of a division using the % operator:
23%6; // the same as asking 'what is the remainderwhen 13 is divided by 6'
<< 5
 

This is similar to, but not quite the same as, modulo arithmetic. That's because the result always has the same sign as the first number:
-4%3; // -4 modulo 3 would be 2
<< -1
 


Changing Variables

If a variable has been assigned a numerical value, it can be increased using the following operation:
points = 0; // initialize points score to zero
<< 0


points = points + 10;
<< 10
  

This will increase the value held in the points variable by 10. You can also use the compound assignment operator, +=, which is a shortcut for performing the same task, but helps you avoid writing the variable name twice:
points += 10;
<< 20
  

There are equivalent compound assignment operators for all the operators in the previous section:


points -= 5; // decreases points by 5
<< 15

points *= 2; // doubles points
<< 30


points /= 3; // divides value of points by 3
<< 10


points %= 7; // changes the value of points to the remainder
if its current value is divided by 7
<< 3
  


Incrementing Values

If you only want to increment a value by 1, you can use the ++ operator. This goes either directly before or after the variable.
So what’s the difference between putting the ++ operator before or after the variable?
The main difference is the value that is returned by the operation. Both operations increase the value of the
points variable by 1, but points++ will return the original value then increase it by 1, whereas ++points will increase the value by 1, then return the new value:
points++; // will return 3, then increase points to 4
<< 3


++points; // will increase points to 5, then return it
<< 5
  

There is also a -- operator that works in the same way:
points--;
<< 5

--points;
<< 3
  

Infinity

Infinity is a special error value in JavaScript that is used to represent any number that is too big for JavaScript to deal with. The biggest number that JavaScript can handle is 1.7976931348623157e+308:
1e308; // 1 with 308 zeroes!
<< 1e308

2e308; // too big!
<< Infinity
  

There is also a value -Infinity, which is used for negative numbers that go below -1.7976931348623157e+308:
-1e309;
<< -Infinity
  

The value of Infinity can also be obtained by dividing by zero:
1/0;
<< Infinity
  

The smallest number that JavaScript can deal with is 5e-324. Anything below this evaluates to either 5e-324 or zero:
5e-324;
<< 5e-324

3e-325;
<< 5e-324

2e-325;
<< 0
  


NaN


NaN is an error value that is short for "Not a Number". It is used when an operation is attempted and the result isn’t numerical:
"hello" * 5;
<< NaN


Type Coercion

Type coercion is the process of converting the type of a value in the background to try and make an operation work. For example, if you try to multiply a string and a number together, JavaScript will attempt to coerce the string into a number:
"2" * 8;
<< 16
  

This may seem useful, but the process is not always logical or consistent, causing a lot of confusion. For example, if you try to add a string and a number together, JavaScript will convert the number to a string and then concatenate the two strings together:
"2" + 8;
<< "28"
  

This can make it difficult to spot type errors in your code, so you should always try to be very explicit about the types of values you are working with.


Converting Between Strings and Numbers

We can convert numbers to strings and vice versa using a variety of methods.


Converting Strings to Numbers

To covert a string into a number we can multiply a numerical string by 1, which will convert it into a number because of type coercion:
answer = "5" * 1;
<< 5


typeof answer;
<< "number"
  

Another neat way of converting a string to an integer is to simply place a + symbol in front of it: 
answer = +"5";
<< 5


typeof answer;
<< "number"
  

Yet another way to convert a string into a number is to use the Number function:
Number("23");
<< 23
  

This is the preferred way to convert strings to numbers as it avoids type coercion in the background. The conversion is explicit, making it obvious what is being done.


Converting Numbers to Strings

To change numbers into strings you can add an empty string, which will use type coercion to silently convert the number into a string in the background:
3 +'';
<< "3"
  

The preferred way, however, is to use the String function:
String(3);
<< "3"
 

There is also the very similar toString() method, but this may change the base of the number. For example, if you want to write the number 10 in binary (base two), you could write:
> 10..toString(2):
<< "1010"
  

You can go up to base 36, although after base ten, letters are used to represent the digits:
> 1000000..toString(36) // a million in base 36
<< "lfls
  


Parsing Numbers

There is also a useful function called parseInt() that can be used to convert a string representation of a numerical value back into an integer. You can specify the base of the number you are trying to convert, for example:
parseInt("1010",2); // converts from binary, back to decimal
<< 10

parseInt("omg",36);
<< 31912


parseInt("23",10);
<< 23
  

If a string starts with a number, the parseInt function will use this number and ignore any letters that come afterwards:
var address = "221B Baker Street"
<< undefined

parseInt(address, 10)
<< 221
 

If you try to do this with the Number function, it returns NaN:
Number(address)
<< NaN
  

And if you use parseInt with a decimal, it will remove anything after the decimal point:
parseInt("2.4",10)
<< 2
  

Be careful not to think that this is rounding the number to the nearest integer; it simply removes the part after the decimal point, as seen in this example:

parseInt("2.9",10)
<< 2
  

There is also a similar function called parseFloat() that converts strings into floating point decimal numbers:
parseFloat("2.9",10)
<< 2.9
  

0 Response to "JavaScript Numbers"

Post a Comment