parseInt() function is adding 1 to my integer, and thus changing the number. What is going on?

49 views Asked by At

I have encountered some behaviour with the JavaScript parseInt function that I have never seen before. I am trying to convert a string to an integer. But the parseInt function is adding 1 to it. The values for temp and k are calculated in a prior step of my program, here is my code:

let temp = 918367346938775;
let k = 5;

console.log("This is temp:", temp);
console.log("This is k:", k);
let concatNumber = temp.toString() + k.toString();
console.log("This is concatNumber in string form:", concatNumber);
console.log("This is concatNumber in integer form using parseInt:", parseInt(concatNumber, 10));
console.log("This is concatNumber in integer form multiplying by 1:", concatNumber * 1);

Here is a picture of the console.log:

Console Log

The string concatenation correctly gives me the number I am expecting which is: 9183673469387755.

However once that number is converted to an integer via parseInt I get 9183673469387756.

I have also attempted to multiply the string by just 1, but I also get the incorrect 9183673469387756 number.

Here is my PlayCodeIO sample:

https://playcode.io/1741191

Why does this happen?

0

There are 0 answers