JavaScript Numbers | JavaScript Functions | Learn JS Online
×

JavaScript Numbers

2629

JavaScript Numbers acts as a wrapper object which permits us to operate numerical values. This can perform entire arithmetic operations like subtraction, modulus, division, and multiplications. In JavaScript, Number object is created via "number() constructor" where as a primitive type number object is created through number() function. JavaScript permits only one type of number. It can be written in both with or without decimals. All types of number systems are compatible with JavaScript including octal, hexadecimal, octal and binary. To declare a number, var and const are used for fixed and constant number respectively.

In JavaScript, the number initiated by 0 is by default octal i.e. 0500 is 8

For Example
var a =5; //number
var e=040; // number in octal

In JavaScript, Number methods and functions are used to convert number into string and strings into number respectively.

Number methods used in JavaScript are toString().toLocalString(), toFixed, toExponential(), toPrecision(1) and toPrecision(3)


toString() method
toString() method used in JavaScript to convert a number into string

Example
var y=8;
y.toString()

output
"8"


toExponential() method
In JavaScript, it converts decimal into exponential notation.

Example
var y=4;
y.toExponential()

Output
"4e+0"


toPrecision(2) method
This method is used to transform decimal into exponential notation.

Example
var y=3.5463;
y.toPrecision(2)

Output
"3.5"


toPrecision(3) method
It transforms decimal into an exponential notation.

Example
var y=3.567889;
y.toPrecision(3)

Output
"3.57"


JavaScript Functions
JavaScript includes number, parseint, and parsefloat functions to converts a string into number. For example var y="45" is string, it will convert this string into number i.e. var y=45.

Number Function
Number function is used to transform string into numbers in JavaScript. This function can transform both floating as well as non-floating integers.

Example

<script>  
 var p="400";
 var q="500.5";
 var r="100px";
 var s="abc100";
   
 p = Number(p)  // 400
 q = Number(q)  // 500.5
 r = Number(r)   // NaN - Not a Number
 s = Number(s)  // NaN - Not a Number
   
 document.write(p+q);     
</script>

Output
900.5



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments