Sunil Lama
Sunil Lama

Reputation: 4539

Javascript 19 digits number changing the last digits to zeroes

I ran into this issue when trying to get the last 4 digits of a 19 digits numeric value.

let payload={
card: 1234567891238475891
}
let stringCardNumber = '' + payload.card;
console.log(payload.card)
console.log(stringCardNumber)
console.log( stringCardNumber.slice(stringCardNumber.length - 4))
let zeroedCardNumber = stringCardNumber.slice(0, 6) + "".padStart(stringCardNumber.length - 10, "0") + stringCardNumber.slice(stringCardNumber.length - 4);
console.log(zeroedCardNumber)

So for 1234567891238475891, the output log is 1234567891238475800.

Changing the card value to string in the json itself is not the solution I am expecting, since there will be cases where 19 digits number is expected.

Upvotes: 1

Views: 1484

Answers (1)

tadman
tadman

Reputation: 211610

That number is too large for JavaScript's default numerical representation so you need to use the longer form with BigInt:

card: 1234567891238475891n

A better approach is to just use a string as these aren't really "numbers" in the conventional sense and as Pointy adds, support for BigInt is a relatively new thing so if support for older browsers is important it won't be a solution.

JSON does not enforce BigInt support, so numerical values this large may well get rounded. Using a string is the most reliable way to ensure this data flows through correctly.

Upvotes: 4

Related Questions