简体   繁体   中英

Javascript slice function returning different values for same value?

im solving a question on hackerrank and i encountered a problem. my slice method is not returning the right value. I was able to recreate using console.log.

 console.log(+("9007199254740993")); console.log("9007199254740993");

why do these return different values?

The biggest value possible for a JavaScript number is 9007199254740991 .

To deal with numbers larger than that you will need to use a BigInt .

 const max = Number.MAX_SAFE_INTEGER; console.log(max); const maxPlusTwo = max + 2; console.log(maxPlusTwo); const maxPlusTwoBigInt = BigInt("9007199254740993"); console.log(maxPlusTwoBigInt.toString());

This link shows the current level of native support for BigInt. Depending on your target platform you may need to use a polyfill for BigInt functionality.

JavaScript has a maximum safe integer limit of 2^53 - 1 ( 9,007,199,254,740,991 ) - it is possible to have numbers greater than this, but it's not very good:

 console.log(9007199254740992 + 200000000001); console.log(Number.MAX_SAFE_INTEGER);

(The above snippet shows they are different - look at the fifth and last digits).

You would have to use an experimental BigInt if you wanted bigger numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM