Number in Javascript - Integer and Float

Javascript

In JavaScript, numbers play a crucial role in performing various operations. They can be integers or floating-point values, and understanding their basics is essential.

// Example of integers
let integerNumber = 42;

// Example of floating-point numbers
let floatNumber = 3.14;

JavaScript Number Constants

JavaScript provides predefined constants for commonly used numbers, making your code more readable.

ConstantDescription
Number.MAX_VALUERepresents the maximum numeric value in JavaScript.
Number.MIN_VALUERepresents the smallest positive numeric value.
Number.POSITIVE_INFINITYRepresents positive infinity.
Number.NEGATIVE_INFINITYRepresents negative infinity.
Number.NaNRepresents “Not a Number” value.
Number.EPSILONRepresents the difference between 1 and the smallest possible next representable number.

Examples include Number.MAX_VALUE and Number.MIN_VALUE.

// Example of using number constants
console.log("Maximum value in JavaScript:", Number.MAX_VALUE);
console.log("Minimum positive value in JavaScript:", Number.MIN_VALUE);

Adding Numbers and Strings

JavaScript allows adding numbers and strings, but their types matter.

// Example of adding numbers and strings
let sum = 5 + "10"; // The result is a string "510"
console.log("Sum of 5 + '10':", sum);

Numeric Strings

Sometimes, numbers may appear as strings. Learn how to convert them to numerical values and vice versa for seamless manipulation.

// Example of converting numeric strings
let numericString = "42";
let numericValue = Number(numericString); // Convert string to number
console.log("Numeric value from string:", numericValue);

NaN - Not a Number

JavaScript uses NaN to represent the result of an undefined or unrepresentable mathematical operation.

// Example of NaN
let resultNaN = "hello" / 5; // This results in NaN
console.log("Result of 'hello' / 5:", resultNaN);

JavaScript Number Methods

Here is the list of all the available methods of Numbers in Javascript.

MethodDescription
Number.toString()Converts a number to a string.
Number.toFixed()Formats a number using fixed-point notation.
Number.toPrecision()Formats a number using specified precision.
Number.toExponential()Converts a number to exponential notation.
Number.valueOf()Returns the primitive value of a Number object.
Number.parseInt()Parses a string argument and returns an integer.
Number.parseFloat()Parses a string argument and returns a floating-point number.
Number.isNaN()Checks if a value is NaN.
Number.isFinite()Checks if a value is a finite number.
Number.isInteger()Checks if a value is an integer.
Number.isSafeInteger()Checks if a value is a safe integer.