Someone knows why
Number(4444444444444444); // (tiene 16 cuatros)
results in
4444444444444444
but
Number(44444444444444444); // (tiene 17 cuatros)
results in
44444444444444450
Someone knows why
Number(4444444444444444); // (tiene 16 cuatros)
results in
4444444444444444
but
Number(44444444444444444); // (tiene 17 cuatros)
results in
44444444444444450
The problem is that:
Number(44444444444444444);
Exceeds the maximum allowed by Javascript for object Number
. There is a constant that calculates this value and you can obtain it with:
Number.MAX_VALUE;
So if you do this:
var biggestNum = Number.MAX_VALUE;
console.log("Máximo admitido: "+ biggestNum);
You will get this on screen:
Máximo admitido: 1.7976931348623157e+308
Number(44444444444444444)
is not a safeInteger , that is, it is not an integer on which you can operate without risk of error . To check if an integer is safe, Javascript has the function Number.isSafeInteger
So if you do this to verify your number:
console.log(Number.isSafeInteger(44444444444444444));
You will get this:
false
Moreover, the same maximum allowed for integers in JS is not safe. If we do:
console.log(Number.isSafeInteger(Number.MAX_VALUE));
We will get:
false
To operate with large numbers you have two exits:
Implement a third-party library managed by bigInteger. For example:
Wait for Javascript to include BigInteger objects
//1. Máximo admitido
var biggestNum = Number.MAX_VALUE;
console.log("Máximo admitido: "+ biggestNum);
//2.
tuNumero=Number(44444444444444444);
console.log("¿Tú número es safeInteger? "+Number.isSafeInteger(tuNumero));
// 3.
console.log("¿El máximo admitido es safeInteger? "+Number.isSafeInteger(biggestNum));
The largest number that can be stored (with precision) in JavaScript is 9007199254740992. The reason why it returns 44444444444444450 is because the JavaScript engine makes an attempt to represent and approximate the value provided.
Then
Number(4444444444444444) = 4444444444444444 (OK, porque es menor al valor maximo permitido)
Number(44444444444444444) = 44444444444444450 (WRONG, porque es mayor al valor maximo permitido)
If you are interested, check out this link link so you can understand in detail how the representation of numbers works.
Greetings Juan Simón
According to the Number documentation, Integers (numbers without a period or exponent notation) are accurate up to 15 digits. link
For example:
var x = 999999999999999; // x sera 999999999999999
var y = 9999999999999999; // y sera 10000000000000000