Number in JavaScript

 

 

Just like the string object the number object can behave as a value type or object.

The number in JavaScript is equivalent to the float in any other programming language but it behaves both as a float or an integer depending on whether the decimal is present.

Assign Value to number

We can either directly assign a value to the number or we use the number constructor to do that.

Maximum value of number

The maximum value of number in JavaScript is 1.7976931348623157e+308 and values larger then this are considered infinity.

Number properties

The various properties available on the number are:

constructor Returns the function that created the Number object’s prototype
MAX_VALUE Returns the largest number possible in JavaScript
MIN_VALUE Returns the smallest number possible in JavaScript
NEGATIVE_INFINITY Represents negative infinity (returned on overflow)
NaN Represents a “Not-a-Number” value
POSITIVE_INFINITY Represents infinity (returned on overflow)
prototype Allows you to add properties and methods to an object

Number methods

The various methods available on number are:

toExponential(x) Converts a number into an exponential notation
toFixed(x) Formats a number with x numbers of digits after the decimal point
toPrecision(x) Formats a number to x length
toString() Converts a Number object to a string
valueOf() Returns the primitive value of a Number objec

 

Source – http://www.w3schools.com/jsref/jsref_obj_number.asp

We can try to parse any string value into integer by using the parseInt method. It can also be used to parse string which contains number in the string.

Number as counter

The most common use of number in JavaScript is as a counter. We use it to keep track of as to how many times we have executed a particular block of code or loops like for, while, etc. Either the number the number is initialized at the start of a function or at global level and the number of times we execute the loop we increment the number and that’s how we know as to how many times we executed our loop.

You will notice that we have used counter++. It is nothing special but a different notation for counter+1

There are situations when we need to use reverse counting in that case we can initialize the counter to some value and the decrement it each time.

counter — is equal to counter – 1.

We could also use ++counter instead of counter++. The difference between them is that when we use ++ before counter then the value of counter is incremented before it is used and when we use ++ after counter the value is incremented after this value is used in the current statement. This will make lot more sense in the below code

Decimal – Binary – Octal – Hex Conversion

Using the number class we can convert the numbers in different formats using the toString() method.

The code for this post can be found here.

Any questions, comments or feedback is really appreciated.