# What do we discuss in this article?

**How to create and use Numbers in JavaScript?****Decimal values/Floating point values****Numeric Range****NaN****Conversions**

## A] How to create and use Numbers in JavaScript?

To create a number, simply create a variable with the *var * keyword and assign it a numeric value as shown below. JavaScript does not have a dedicated numeric data type like other languages such as C, C++, Java etc.

1 |
var myNumber=85; |

To store octal [a number with only 8 digits 0-7] or hexadecimal [a number with 16 digits 0-F] values inside a variable, use the trick below. If you are running **strict mode, **invalid octals or hexadecimals will throw an error.

1 2 3 4 5 |
var myOctal1=070; //Contains the decimal value 56 //This is an invalid number since octal numbers have digits 0-7 only //JS converts invalid octal numbers to plain old decimal numbers var myOctal2=088; |

To create hexadecimal value, use a 0x [small x] as shown below.

1 2 |
var myHex1=0xA8; //Decimal value=168 |

Numbers created using octal or hexadecimal format are treated as decimal numbers in all arithmetic operations.

## B] Decimal/ Floating Point Numbers

To define a floating-point value, you must include a decimal point and at least one number after the decimal point. Although an integer is not necessary before a decimal point, it is recommended.

1 2 3 |
var myFloat1=4.6; var myFloat2=2.3; var myFloat3=.5; //valid but not recommended |

Floating-point values uses twice as much memory as storing integer values hence when JS engine finds no digit after the decimal point, it converts the number automatically into an integer.

1 2 |
var myNum1=2.; //considered as integer 2 var myNum2=4.0; //considered as integer 4 |

Use the **e notation **to represent very small or very large numbers. 500,000 can be written as 5e5

1 2 3 4 |
var myLargeNum=5e5; alert(myLargeNum); //prints 500,000 in your browser if you test it |

0.0003 can be written as 3e-4

1 2 3 4 |
var mySmallNum=3e-4; alert(mySmallNum); //prints 0.0003 on your browser |

** Floating Point Numbers are NOT Accurate while performing Arithmetic computations.**

1 2 3 4 5 |
var num1=0.1; var num2=0.2 alert(num1+num2); //Guess what's the answer |

Since their operations are not accurate, avoid doing *if(x+y==0.3){ alert(“Yay you got the answer!”); }*

Rounding errors occur because of the way they are performed using the IEEE-754 floating point arithmetic specification. These issues exist in other languages that follow the same spec.

## C] Numeric Range

What is the largest and smallest number JavaScript can work with?The smallest number that can be represented in JavaScript is stored in Number.MIN_VALUE and is 5e-324 on most browsers. The largest number is stored in Number.MAX_VALUE and is 1.7976931348623157e+308 on most browsers.

1 2 3 4 5 |
var message="The smallest number is " +Number.MIN_VALUE +"\n The largest number is " +Number.MAX_VALUE; alert(message); |

If a calculation results in a number that cannot be represented by JavaScript’s numeric range, the number automatically gets the special value of Infinity.

1 2 3 4 |
var message=2*Number.MAX_VALUE; alert(message); //prints infinity |

Any negative number that can’t be represented is –Infinity, and any positive number that can’t be represented is simply Infinity. You can test a variable to check if it contains a value of Infinity or not by using the **isFinite()** function.

### 1)Example of **isFinite()** function

Create two variables, let one of them have a finite value and let the other one have an infinite value. Test the isFinite() function on both. It returns a boolean with either true or false as the result. If the number is NOT INFINITE, the result is true else the result is false.

1 2 3 4 5 6 7 8 9 10 |
var num1=18841; //Finite var num2=2*Number.MAX_VALUE; //Infinite var test1=isFinite(num1); //true var test2=isFinite(num2); //false var result="Test for Num 1 "+test1 +"\nTest for Num 2 "+test2; alert(result); |

** Number.NEGATIVE_INFINITY and Number.POSITIVE_INFINITY store the special values -Infinity and Infinity.**

## D] NaN

NaN= Not a Number. It’s a special value which arises when an operation results in something which is not a number. For example, dividing any number by 0 will yield NaN.

**Properties of NaN**

- Any operation on NaN returns NaN, example: NaN/1000=NaN
- NaN==NaN is false which means NaN is not equal to any value including itself.
- Use the
**isNaN()**function to check if the value contained in a variable is not a number. - When a variable is provided to
**isNaN()**function, JS interpreter tries to convert it into a number.

Value supplied to isNaN() | Result |
---|---|

isNaN(NaN) | true |

isNaN(30)//30 is a valid number, so false | false |

isNaN(“65″)//”65” string can be converted to 65 number, so ultimately it is valid | false |

isNaN(“orange”)//”orange” string CANNOT be converted to a number | true |

isNaN(false)//false can be converted to number 0 and since 0 is a number, isNaN returns false | false |

## E]Numeric Conversions

The three functions that convert non-numeric values into numbers are **Number(), parseInt(), parseFloat(), Number() **works on all the data types, the remaining two can be used only on string values.

### 1)The Number() Function

Apply Number() function on variable | Becomes |
---|---|

boolean value true |
1 |

boolean value false |
0 |

numeric value | Value unchanged |

null value |
0 |

undefined value |
NaN |

a String with only numeric values like “789” |
789 |

a String with decimal numbers like “03.14” |
3.14 //ignores leading zeroes and converts to floating point number |

a String with leading zeroes “055” |
55 //leading zeroes are ignored in String |

a String with leading zeroes and HEX characters “0xF” |
16 //converts String to integer matching the hex value F |

a String which is empty “” |
0 |

a String with anything else “85blue”,”orange” |
NaN |

an Object. valueOf() is called for that object and an attempt is made to convert the result using the above rules. If valueOf() returns NaN, toString() for the object is called and string conversion rules are applied.[Don’t worry about Objects at this point if you are not aware of them. As we said earlier, we’ll dig into Objects once you are ready with other basic stuff.] |
NaN or some numeric value |

Enough rules!, let’s take an example to understand how the Number() function converts stuff.

1 2 3 4 5 6 7 8 |
var num1 = Number("Hello world!"); //NaN var num2 = Number(""); //0 var num3 = Number("000011"); //11 var num4 = Number(true); //1 var num5=Number("bad185"); //NaN var num6=Number("0xFF");//255 var num7=Number(undefined);//NaN var num8=Number(null);//0 |

The string “Hello world” is converted into NaN because it has no corresponding numeric value, and the empty string is converted into 0. The string “000011” is converted to the number 11 because the initial zeros are ignored. The value true is converted to 1.

### 2) The parseInt() Function

**parseInt()** function in JavaScript is used for generating a numeric representation of a String. Its working is illustrated below.

- Ignore all white spaces at the start of the string
- if the first character is number or minus sign or plus sign, return that character
- Check if the subsequent character is also a number.
- If yes, proceed and extract as many numbers as you can till the end of the String or till the first non-numeric character is encountered.
- If no, stop.

- If the first character is not a number, – or + , return NaN and don’t process anything further.

“1234orange” is converted to 1234 because “orange” is completely ignored. Similarly, “22.5” will be converted to 22 because the decimal is not a valid integer character. parseInt() can also detect octal, hexadecimal values along with the usual decimal. When the string begins with “0x”, it is interpreted as a hexadecimal integer; if it begins with “0” followed by a number, it is interpreted as an octal value.

1 2 3 4 5 6 |
var num1 = parseInt(“1234blue”); //1234 var num2 = parseInt(“”); //NaN var num3 = parseInt(“0xA”); //10 - hexadecimal var num4 = parseInt(22.5); //22 var num5 = parseInt(“70”); //70 - decimal var num6 = parseInt(“0xf”); //15 - hexadecimal |

** parseInt()** can also accept a second argument, here’s how you can use that. If you know that the value you’re parsing is in hexadecimal format, you can pass in the radix 16 as a second argument and ensure that the correct parsing will occur.

1 |
var num = parseInt(“0xAF”, 16); //175 |

So, here is a little insight of what will happen with and without a radix for a string that looks just like a hex value.

1 2 |
var num1 = parseInt(”AF”, 16); //175 var num2 = parseInt(”AF”); //NaN |

The difference is that the radix is passed in on the first line, telling **parseInt()** that it will be passed a hexadecimal string. The second line sees that the first character is not a number and stops automatically returning NaN. Different values of radix can yield different outputs.

1 2 3 4 |
var num1 = parseInt(“10”, 2); //2 - parsed as binary var num2 = parseInt(“10”, 8); //8 - parsed as octal var num3 = parseInt(“10”, 10); //10 - parsed as decimal var num4 = parseInt(“10”, 16); //16 - parsed as hexadecimal |

### 3) The parseFloat() function

**parseFloat()** is used to generate a floating point based numeric representation of a String value as illustrated below.

- The
**parseFloat()**function works in a similar way to**parseInt()**looking at each character starting in position 0. - It also continues to parse the string until it reaches either the end of the string or a character that is invalid in a floating-point number.
- A decimal point is valid the first time it appears, but a second decimal point is invalid and the rest of the string is ignored, resulting in “22.34.5” being converted to 22.34.
**parseFloat()**ignores initial zeroes from the String value.- Hexadecimal numbers always become 0 since parseFloat() parses only decimal values. It does not support radix mode like
**parseInt().** - If the string represents a whole number with no decimal point or only a zero after the decimal point
**parseFloat()**returns an integer. - Here is an example of the different scenarios and the result for each using
**parseFloat().**

1 2 3 4 5 6 |
var num1 = parseFloat(“1234blue”); //1234 - integer var num2 = parseFloat(“0xA”); //0 var num3 = parseFloat(“22.5”); //22.5 var num4 = parseFloat(“22.34.5”); //22.34 var num5 = parseFloat(“0908.5”); //908.5 var num6 = parseFloat(“3.125e7”); //31250000 |

# CONCLUSION

Use **parseInt()** with radix for converting a string that contains numbers to a numeric value. Use **parseFloat()** if you know your String contains decimals. Use **Number()** as a last resort if you cannot accomplish your task using the above 2 methods. In the next post, it’s time to dig into Strings in JavaScript.