0

Good day, I am currently in bit confusion between Data type "number" and data type "Integer" in JavaScript. can anyone explain and gives example.

Dexygen
  • 12,287
  • 13
  • 80
  • 147
RIchard
  • 17
  • 2
  • JS is unusual in not having any "integer" type. There is just "number" which covers both integers and floating point numbers – Robin Zigmond Aug 05 '21 at 19:43
  • Does this answer your question? [What is the difference between parseInt() and Number()?](https://stackoverflow.com/questions/4090518/what-is-the-difference-between-parseint-and-number) – LeeLenalee Aug 05 '21 at 19:43
  • So how can you define integer data type and give contents if possible? – RIchard Aug 05 '21 at 19:51
  • @Richard: There is not an integer data type in JavaScript. Just use integer numbers. If you have arithmetic operations that have fractional results use the Math.floor() function to convert the result to an integer value. – Escovado Aug 05 '21 at 20:14

2 Answers2

0

In js you have different type of variables (number, string, object, etc). But there isn´t an integer or float data type (not like in c or c++). It means that all integers and floating numbers are typeof number:

let integer = 10;
let float = 10.5;

console.log(typeof integer); /* number */
console.log(typeof float);   /* number */

But if you want to check if number is an integer or a float, you can do use Number.isInteger() method and check whereas a variable is integer or not:

let integer = 10;
let float = 10.5;

console.log(Number.isInteger(integer));  /* True */

console.log(Number.isInteger(float));    /* False */
AlexSp3
  • 2,201
  • 2
  • 7
  • 24
0

Because all integers are numbers, but not all numbers are integers. JavaScript has only floating point numbers. An integer is a whole number with no fractional value (zeros to the right of the decimal point). An example usage of the Number.isInteger() JavaScript function from Mozilla's web site should help:

Number.isInteger(0);         // true
Number.isInteger(1);         // true
Number.isInteger(-100000);   // true
Number.isInteger(99999999999999999999999); // true

Number.isInteger(0.1);       // false
Number.isInteger(Math.PI);   // false

Number.isInteger(NaN);       // false
Number.isInteger(Infinity);  // false
Number.isInteger(-Infinity); // false
Number.isInteger('10');      // false
Number.isInteger(true);      // false
Number.isInteger(false);     // false
Number.isInteger([1]);       // false

Number.isInteger(5.0);       // true
Number.isInteger(5.000000000000001); // false
Number.isInteger(5.0000000000000001); // true

Note that that the last example identifies "5.0000000000000001" as an integer probably because it goes beyond the precision of the parser.

Use the Math.floor() function to truncate the fractional value of a floating point number to an integer.

Escovado
  • 116
  • 10