Tut#4 JavaScript Numbers, Range, NaN, Floating Point Values, and Conversions

What do we discuss in this article?

  1. How to create and use Numbers in JavaScript?
  2. Decimal values/Floating point values
  3. Numeric Range
  4. NaN
  5. 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.

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.

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

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.

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.

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

0.0003 can be written as 3e-4

 Floating Point Numbers are NOT Accurate while performing Arithmetic computations.

javascript floating values

slidenerd

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.

javascript numeric range

slidenerd

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.

javascript infinity

slidenerd

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.

JavaScript isFinite example

slidenerd

  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

  1. Any operation on NaN returns NaN, example: NaN/1000=NaN
  2. NaN==NaN is false which means NaN is not equal to any value including itself.
  3. Use the isNaN() function to check if the value contained in a variable is not a number.
  4. 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.

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.

JavaScript parseInt() example

slidenerd

  • 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.

 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.

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.

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.

 3) The parseFloat() function

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

JavaScript parseFloat() function

slidenerd

  • 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().

 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.