Site icon Eval

JavaScript Tutorial & Demo 8: JavaScript Numbers

JavaScript Numbers

JavaScript Numbers: Integer, floating-point, long, double, etc. are not supported in JavaScript like in C++, C#, and Java, all of which belong to the object-oriented programming family. There is just one kind of Number in JavaScript: a floating-point number. All calculations are performed with 64-bit (8-byte) floating-point numbers. JavaScript lacks the number-defining data types seen in languages like C and C++ (recently, with ECMAScript2016, JavaScript has started supporting the BigInt type for integers).

JavaScript supports double-precision 64-bit binary formats for numbers, much as the double data type in C# and Java, making it possible to work with positive and negative integers, floating-point (decimal) numbers, binary, octal, hexadecimal, and exponential values. It uses various sets of numbers as specified by the worldwide IEEE 754 standard.

Today’s versions of JavaScript support two distinct kinds of numeric values:

JavaScript uses IEEE-754, a 64-bit standard for storing integers, often known as “double precision floating point numbers,” for all of its regular numbers. This section will discuss the most common numerical values in use.

Integers of undefined length can be represented as BigInt numbers. It’s not safe to go over or below -253 with a normal number; thus, they are occasionally required. Bigints have limited use; therefore, we’ve devoted an entire chapter to them here.

Integer numbers

Whether positive or negative, integers can have any sign. However, in JavaScript, integers are treated as floating-point numbers. JavaScript will preserve 15 decimal places of precision for integer values. BigInt should be used for numbers with more than 15 digits so that they are not modified and rounded as necessary.

Floating-point numbers

There is an accuracy limit of 17 decimal digits for JavaScript’s floating-point integers; any numbers after that will be rounded down.

Example: Floating-point Numbers in JavaScript

//17 decimal places
var a1 = 123456789012345.9; //accurate 
//18 decimal places
var a2 = 1234567890123456.9; //will be 1234567890123457 
//19 decimal places
var a3 = 1234567890123456.79; //will be 1234567890123456.8

Big Integers

BigInt is a primary numeric type that can hold integers to any precision. Large integers with more digits than 15 should be stored in a BigInt. To transform a regular integer into a BigInt, add n to its end.

Example: Integers in JavaScript

//16 digit integer
var int1 = 1234567890123459n; //will be 1234567890123459
//17 digit integer
var int2 = 12345678901234569n; //will be 12345678901234569
//20 digit integer
var int3 = 9999999999999999999n; //will be 9999999999999999999

Binary, Octal, Hexadecimal, Exponential

A 0b or 0B followed by a 0 or 1 is required as the first digit in binary.

All octal digits must begin with either zero or the lowercase or uppercase letter ‘O,’ 0o, or 0O.

All Hexadecimal digits must be prefixed with either 0x or 0X, the zero, and the character ‘X.

The exponentials should be written in the form bN, where b is the base number (an integer or float followed by an e char), and N is the exponential power.

Ways to write a number in Javascript

The decimal system is the most used way to record numerical data. However, there are methods for representing numeric values in javascript.

Decimal Method

The decimal number system is the one most often used in everyday life. Decimal digits can be any value from 0 to 9. Decimal numerals are defined by utilizing digits between 0 and 9.

Example

const n1 = 80;
const n2 = 12.34;
console.log(n1, n2);

Exponential Method

If we were to write 1 billion or 1 trillion in numbers, we’d have to register them like this: 100000000 or 10000000000.

JavaScript has a tool that makes it simpler to type in large numbers. If we add an e or an E to the number and then tell it how many zeroes to drop, we get a shorter version of the original. The notation for 1000 is 1e3, for 0.002 it’s 2e-3, for 50,000 it’s 5e-4, and so on. The exponential notation is used here.

Example

const n1 = 44e2;
console.log(n1);
const n2 = 1e9;
console.log(n2);
const n3 = 123456e-4;
console.log(n3);
const n4 = 0.00124e11;
console.log(n4);
const n = 99995e-9;
console.log(n5);

Other Number System

Besides the familiar base ten systems, various numerical representations are available, such as binary, octal, hexadecimal, etc.

The hex color scheme relies heavily on the hexadecimal number system.

The prefix 0x indicates that the number is a hexadecimal representation. Such like 0xff, 0x25, etc.

Example

const n1 = 0xff;
const n= 0xFF; // case doent't matter -- 255
const n= Number(0x22);
const n= Number(0x1e2);
console.log(n1, n2, n3, n4);

To simplify things, binary numerals only use the values 0 and 1. For a definition, append the digit 0b to the end of the integer. In the range 0b1010, 0x11, etc.

Example

const n1 = 0b1111;
const n2 = 0b1010;
const n3 = Number(0b1000001);
const n4 = Number(0b111110001);
console.log(n1, n2, n3, n4);

The numerals 0 through 9 are all octal, as are the numbers 5, 6, and 7. To identify it, append the digit 0o to the end of the original number. A few illustrations are 0o55, 0o33, etc.

Example

const n1 = 0o8;
const n2 = 0o55;
const n3 = Number(0o10);
const n4 = Number(0o655);
console.log(n1, n2, n3, n4);

JavaScript has two special types of numbers: Infinity and NaN.

Syntax

<script>
console.log(typeof(Infinity)) //Number
console.log(typeof(NaN)) //Number
</script>

Infinity

Infinity or negative infinity can be returned from a JavaScript expression. You get infinity if you divide any number by zero.

Example

<script>
console.log(2/0); //Infinity
console.log(-2/0); //-Infinity
</script>

NaN – Not a Number

A result of a JavaScript expression can be the NaN value. NaN is returned, for instance, when a string is divided by a number.

Example

<script>
console.log("Hey"/2); //NaN
console.log("Hey"-2); //NaN
</script>

If the values of your JavaScript expression are strings, the plus (+) operator will function as a concatenation operator, and your expression will not return NaN.

Example

<script>
console.log("Hello"+2); //Hello2
</script>

Numbers As Objects

Introducing a new term allows for the definition of numerical values as objects. Using numbers as an object is discouraged because of the performance hit they cause.

Example

<script>
var x = 4; //number
var y = new Number(4); //object
console.log(typeof(x)) //number
console.log(typeof(y)) //object
</script>

Javascript Number methods

JavaScript provides us with number-related aid in the form of numerical methods. However, when we invoke methods on a basic value like 2, 18, etc., JavaScript interprets it as an object even if it cannot have properties and methods.

isNaN In Javascript

The isNaN() function checks if the sent-in value is NaN (Not a Number) globally. It returns true if the given value is NaN and false otherwise.

Why do we need the isNaN method?

NaN values cannot be compared with one another, unlike other values in JavaScript. Given that NaN == NaN and NaN === NaN are both invalid assumptions. Therefore, the isNaN technique is required to determine whether or not a given integer is a NaN.

Example

console.log(isNaN(NaN));
console.log(isNaN(20));
console.log(isNaN("xyz"));
console.log(isNaN());

isFinite In Javascript

The provided value may be checked to see if it is a finite number by calling the global function isFinite(). In addition, that is done if the provided value can be represented numerically.

This method will return false if the parameter is NaN, positive infinity, or negative infinity, and true otherwise.

Example

console.log(isFinite("10"));
console.log(isFinite(100));
console.log(isFinite(1000));
console.log(isFinite("xyz"));
console.log(isFinite(NaN));
console.log(isFinite(Infinity));
console.log(isFinite(-Infinity));

isInteger In Javascript

Whether or not a given number is an integer may be checked with the isInteger() function.

This function returns false if the parameter is not a number or is infinitely large or infinitely little, respectively, and returns true otherwise.

Example

console.log(Number.isInteger(10));
console.log(Number.isInteger(Math.PI));
console.log(Number.isInteger(15.15));
console.log(Number.isInteger(-15));
console.log(Number.isInteger(true));
console.log(Number.isInteger(NaN));
console.log(Number.isInteger(Infinity));
console.log(Number.isInteger(-Infinity));

isSafeInteger In Javascript

The isSafeInteger() function checks if the input value is a valid integer.

A secure integer is a precise representation of a double-precision IEEE-754 number. Numbers between -253 and 252 inclusive (253 – 1).

If the value is a safe integer of type Number, the isSafeInteger() function will indicate such by returning true.

Example

console.log(Number.isSafeInteger(10));
console.log(Number.isSafeInteger(Math.PI));
console.log(Number.isSafeInteger(Math.pow(2, 42) - 1));
console.log(Number.isSafeInteger(-(Math.pow(2, 42) - 1)));
console.log(Number.isSafeInteger(Math.pow(2, 42)));
console.log(Number.isSafeInteger(NaN));
console.log(Number.isSafeInteger(Infinity));

parseFloat In Javascript

A floating-point number is returned from the Number.parseFloat() or parseFloat() function after the input is parsed. The value NaN is returned if the input number cannot be converted.

To extract numbers from physical quantities such as “75kg,” “110px,” “110km,” etc., you may use this tool.

The value NaN is returned if the initial character cannot be transformed into a number.

Example

console.log(parseFloat("55kg"));
console.log(parseFloat("110.65px"));
console.log(parseFloat("xyz"));

parseInt In Javascript

Number.parseInt(), also written as parseInt(), is identical to the parseFloat function except that it returns an integer value instead of a floating-point one.

parseInt additionally takes radix as an optional input (the base in a mathematical number system).

NaN is returned if the initial character provided cannot be translated to a numeric value.

Example

console.log(parseInt("75kg"));
console.log(parseInt(123.0234));
console.log(parseInt("n100"));

toExponential Method In Javascript

The Integer.toExponential() function takes in a number and produces a string in exponential notation.

To choose the number of significant digits following the decimal point, you can pass an optional integer parameter to this function.

Example

const num1 = 53455;
const num2 = 8362926;
console.log(num1.toExponential());
console.log(num2.toExponential(5));
console.log(Number.parseInt(3929).toExponential());

toFixed Method In Javascript (round number)

It uses fixed-point notation, the integer.toFixed() function in JavaScript converts a given number into the appropriate format. In this context, “any” number of digits is the number number of digits that will be shown.

With the Number.toFixed() function, you may set the number of digits displayed after the decimal point by providing a numeric value as an argument.

The numbers are rounded in the same way they would be in mathematics.

Example

const n1 = 1.23455;
const n2 = 6.78912;
console.log(n1.toFixed());
console.log(n2.toFixed(2));
console.log(Number.parseFloat(2.592).toFixed(2));

toLocaleString Method In Javascript (format number)

Converting a Date object to a string according to the standards of the current locale is the responsibility of the number.toLocaleString() function.

It takes a locale parameter to determine the local time zone. You may see this in the language codes for UK (en-UK), India (en-IN), US (en-US), etc.

Example

const today = new Date();
console.log(today.toLocaleString('en-UK'));
console.log(today.toLocaleString('en-IN'));
console.log(today.toLocaleString('en-US'));

toPrecision Method In Javascript

To return a string representation of the number, the integer.toPrecision() function rounds the result up to the provided number. As an illustration, the accuracy of 125000 is 3.

An argument of any size can be used to specify the level of accuracy desired by this procedure.

Example

const n1 = 123456;
const n2 = 123.456789;
console.log(n1.toPrecision(2));
console.log(n2.toPrecision(3));

toString Method In Javascript (number to string)

As its name implies, the Number.toString() function takes a number as an argument and outputs a string representing that number.

The number system’s base can be an optional parameter to this procedure. If parameterized as 2, the number will be serialized as a binary string. 10 is its default value.

Example

const n1 = 200;
const num2 = 9;
console.log(n1.toString(16));
console.log(n1.toString(8));
console.log(n2.toString(2));

valueOf Method In Javascript

For each given object, the Number.valueOf() function will return a primitive number.

Example

const n1 = new Number(63);
console.log(n1.valueOf());
console.log(typeof n1.valueOf(), typeof n1);

Static properties of Numbers

Static attributes of Numbers in JavaScript, such as MAX VALUE and MIN VALUE, have predetermined values. NaN is used to verify if the value is not a number and ease various activities using Numbers. Come, let us examine them closely.

EPSILON

EPSILON is a JavaScript property that returns the lowest possible number representation gap between two numbers.

MAX_SAFE_INTEGER

Use the MAX SAFE INTEGER property to find the best possible safe integer in JavaScript. This value is (*253-1*).

MIN_SAFE_INTEGER

The MIN SAFE INTEGER property returns [*-(253-1)*] as the smallest safe integer in JavaScript.

MAX_VALUE

The MAX VALUE function always gives the maximum value.

MIN_VALUE

To get the lowest non-negative number, closer to zero than any other, use the MIN VALUE attribute.

NaN : To indicate that a value is “Not a Number,” you might use the NaN attribute. NaN refers to a value that is not a number.

POSITIVE_INFINITY

Using the POSITIVE INFINITY property to express a positive infinity when working with JavaScript.

NEGATIVE_INFINITY

NEGATIVE INFINITY is the JavaScript property for the negative infinity value.

Prototype

This property is a prototype for extending the functionality of Number objects with additional features.

Examples

// largest possible value
const a = Number.MAX_VALUE;
console.log(a); // max-value -> 1.7976931348623157e+308
// maximum safe integer
const a = Number.MAX_SAFE_INTEGER;
console.log(a); // min-value -> 9007199254740991

Static methods

Static Number methods are available in JavaScript. We have already covered them earlier but let us look at them one more time:

isFinite()

The isFinite() function determines if the given value is a finite number.

isNaN()

If the parameter is NaN, the isNaN() function returns true.

isInteger()

It checks if the value supplied is an integer using the isInteger() function.

isSafeInteger()

Is the supplied value a safe integer? This method will tell you that

parseInt(string, [radix])

parseInt(string, [radix]): This function parses a string of digits and returns an integer.

parseFloat(string)

The parseFloat(string) function is used to cast a floating-point string to an integer (Number with a decimal point)

Examples

The parseInt() static function was used to turn the string “07” into the integer 7 in the first example below.

To test if the value in variable bis is not a number, we utilized the NaN() static function in the second example below.

The isInteger() static function was used to determine if the value stored in the variable c is an integer in the third example below.

// 1st
const x = parseInt('07');   // it returns 7 as an integer
console.log(x);
// 2nd
const y = NaN;
console.log(Number.isNaN(z)); // it returns true because NaN is not a number
// 3rd
const z = 21;
console.log(Number.isInteger(z)); // it returns true because z is an integer

Instance methods

Some methods in JavaScript’s Numbers class are “instance methods,” meaning they apply only to a single object. Okay, let’s have a look at them.

toFixed(fractionDigits)

You may get the fixed-point representation of a number using the toFixed(fraction digits) function, which produces a string.

toExponential(fractionDigits)

This function, toExponential(fraction digits), converts a number into exponential notation and returns it as a string.

valueof()

The value of() is a function that returns the actual numerical value.

toPrecision(precisionNumber)

This function, toPrecision(precision number), takes in a number and returns a string with the number written down to a given level of accuracy.

toString(radix)

It converts numeric numbers to string form using the specified radix. Radix is not required to be passed on in this case and can be omitted.

If you don’t specify a radix or base when calling toString(), you’ll get a string with the default radix of 10.

toLocaleString()

You may get a string formatted for the user’s language and country using the toLocaleString() function.

Example

Using the toFixed() instance function, we limited a’s value in the first example below to only two digits. So, the result is merely 1.23.

Use the toExponential() instance function to see the d’s value expressed as an exponential in the second example below. So, the result is 1.23456e+5 for the value 123456.

The value of variable b was determined using the valueOf() instance function in the third example. Because of this, it gives us a result of 35.

Below, in Example 4, we utilize the toPrecision() instance function to round the integer to the requested precision (2 in this case). For this reason, 55 is the answer.

The toString() instance function converts the integer 25 to the string 25 in the fifth example below.

Example 6 below uses the toLocaleString() instance function to obtain the localized string representation of the specified integer. Here, we’ve also supplied an object to indicate the format; in this example, it’s Indian Rupee using the hi-IN Hindi currency format (India). As a result, we paid 1000.00 for a value of 1000.

// 1st
let a = 1.23456;
console.log(a.toFixed(2)); // this will return 1.23
// 2nd
let b = 123456;
let b_toExpo = b.toExponential();
console.log(b); // this will return 123456
console.log(b_toExpo); // this will return 1.23456e+5
// 3rd
let c = 35;
console.log(c.valueOf()); // this will return the value i.e. 35
// 4th
let d = 55.447766;
console.log(d.toPrecision(2));// this will return 55
// 5th
let e = 25;
console.log(e.toString()); // this will return a numeric string i.e. 25 as a String.
// 6th
var f = new Number(1000);
var fObj = {
  style: "currency",
  currency: "INR" // Indian Rupee
}
console.log(f.toLocaleString("hi-IN", fObj)); // Output will be ₹1000.00

Rounding

For reasons we’ve already gone over, rounding off with JavaScript can occasionally lead to unexpected mistakes or outcomes. That’s because JavaScript sometimes does weird things while rounding. It would be helpful to see some additional cases so we can study them.

Example

// Here, we are doing the non-decimal number accuracy test
var a1 = 999999999999999; //15 digits number
console.log(a1); // here we get accurate result -> 999999999999999
var b1 = 9999999999999999; //16 digits number 
console.log(b1); // here we get a rounded off value -> 10000000000000000
var c1 = 8999999999999999; //16 digit number
console.log(c1); // here we get the accurate result -> 8999999999999999
//Here, we are doing the decimal number accuracy test
var a2 = 1.999999999999999; //16 digits number
console.log(a2); //here we get accurate result -> 1.999999999999999
var b2 = 1.9999999999999999; //17 digits number
console.log(b2); //here we get rounded off result as it is a 17 digit integer -> 2
var c2 = 11.999999999999999; //17 digits number
console.log(c2); //here we get to see a different behaviour in rounding off hence we get an unpredicted result -> 11.999999999999998

This has shown that rounding off results in JavaScript is unexpected when dealing with huge numbers, as seen in the above examples. However, that begs the question: why? This happens when a JavaScript program tries to utilize an integer value larger than the maximum allowed (Number.MAX SAFE INTEGER). The term “MAX SAFE INTEGER” implies that any numbers above that point are not guaranteed to behave as expected.

Precision Problems

Since every Number in JavaScript is a float by default, which only supports 17 decimal places, any numbers with more than 17 digits are truncated. Unfortunately, this practice of unnecessary rounding off causes issues with accuracy. Some illustrations are shown below.

Examples

The expected result, in this case, 12,5, is obtained in the first scenario below.

We receive an unexpected result in the second case below because of a lack of accuracy.

// 1st
let a1 = 3.2 + 2.3; 
console.log(a1) // Output will be 5.7
// 2nd
let a2 = 12.1 + 12.2;
console.log(float_2) // We want 24.3 as output but it will give 24.299999999999997

To solve this problem, we can use this method:

let a3 = (12.1*100 + 12.2*100)/100;
console.log(a3) // accurate result is obtained using the above method. i.e.

Article Category: JavaScript Tutorials

More JavaScript Tutorials

Exit mobile version