Sum function with a large value returns a wrong result

Asked

Viewed 189 times

4

Why is my summation function returning to me 633223344234234200000 and not 633223344234234234235?

function plus(n) {
    return n+1;
}

console.log(plus(633223344234234234234))

  • Due to the maximum amount of significant digits that the data type can store?

2 answers

8

It turns out that in Javascript a number is represented as Number. According to the specification (in free translation):

Type Number has exactly 18437736874454810627 (i.e., 264 - 253 + 3) values representing the values IEEE 754-2008 double-precision 64-bit format, as per specified in the IEEE Standard for binary floating point arithmetic (...)

Knowing that a number is represented as Number, you can take a look at Number.MAX_SAFE_INTEGER. And according to the MDN documentation, "Safe, in this context, refers to the ability to represent integers exactly and compare them correctly.". See:

console.log(Number.MAX_SAFE_INTEGER)
console.log(Number.MAX_SAFE_INTEGER + 1)
console.log(Number.MAX_SAFE_INTEGER + 2)
console.log(Number.MAX_SAFE_INTEGER + 1 === Number.MAX_SAFE_INTEGER + 2)

Ok, now that we understand about the "limit", what happens in your case is a "rounding". If you need to perform this operation, you can use the BigInt:

function plus(n) {
  return BigInt(n) + BigInt(1);
}

const soma = plus('633223344234234234234');
console.log(soma.toString());

Note that you need to pass the "big" value as String to the BigInt, because if we use it as a number (BigInt(633223344234234234234)), we will actually be passing a rounded value.

8


In Javascript the default type to work with numbers is Number which represents a floating point value of double precision (64 bits) following the standard IEEE 754.

According to IEEE 754 only numbers can be safely represented between-(2^53 - 1) and 2^53 - 1. These limits can be checked by means of the:

To be able to work with numbers beyond safety limits, Number.MAX_SAFE_INTEGER and Number.MIN_SAFE_INTEGER, Javascript must use the type BigInt.

A BigInt is created with the addition of the suffix n at the end of a literal integer or calling the function BigInt().

BigInt cannot be used with methods in the object Math and cannot be mixed in operations with instances of Number.

function plus(n) {
  //Caso n seja BigInt realiza a soma com parcelas do tipo BigInt 
  //usando a função BigInt() senão realiza a operação padrão.
  return n + (typeof(n) == `bigint` ? BigInt("1") : 1);
}

// Tentativa de gerar um inteiro maior que Number.MAX_SAFE_INTEGER
let normal = 633223344234234234235;

// Gerando um inteiro de tamanho arbitrário usando o sufixo n
let big = 633223344234234234235n;

console.log(`Utilizando inteiros convencionais ${plus(normal)}`);

console.log(`Utilizando inteiros arbitrários ${plus(big)}`);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.