gpt4 book ai didi

javascript - 如果我需要数 9,007,199,254,740,993 怎么办?

转载 作者:行者123 更新时间:2023-11-30 05:33:48 24 4
gpt4 key购买 nike

我正在阅读 David Herman 的 Effective Javascript,并且刚刚了解了 JavaScript 如何处理数字:

"all numbers in JavaScript are double-precision floating-point numbers, that is, the 64-bit encoding of numbers specified by the IEEE 754 standard -- commonly known as "doubles". If this fact leaves you wondering what happened to the integers, keep in mind that doubles can represent integers perfectly with up to 53 bits of precision. All of the integers from -9,007,199,254,740,992 (-2^53) to 9,007,199,254,740,992 (2^53) are valid doubles." (p. 7)

我很好奇,所以我拼凑了this jsfiddle尝试一下:

var hilariouslyLargeNumber = 9007199254740992;

console.log(hilariouslyLargeNumber);
// 9007199254740992
console.log(hilariouslyLargeNumber + 1);
// 9007199254740992

console.log (hilariouslyLargeNumber === hilariouslyLargeNumber);
// true
console.log(hilariouslyLargeNumber === hilariouslyLargeNumber+1);
// true
console.log(hilariouslyLargeNumber === hilariouslyLargeNumber-1);
// false

有点理解为什么会这样——在简单(简单,简单)的语言中,对于 JavaScript 如何编码数字,不再有更多的 0 和 1 的“插槽” , 所以它必须停止在 9,007,199,254,740,992。

那么:如果我发现自己拥有 9,007,199,254,740,993 只小狗,并且想编写一些代码来帮助我记住哪只小狗,我该怎么办?我需要使用 JavaScript 以外的东西吗?如果是,为什么?

最佳答案

您必须进行一些变通编程。一个例子是:

var MAX_VALUE = 9007199254740992;

var lower_digit_set = 0;
var upper_digit_set = 0;


/* Do some calculations that will eventually result in lower_digit_set to be 9007199254740992 */

lower_digit_set = MAX_VALUE;

if (lower_digit_set == MAX_VALUE) {
lower_digit_set = 0;
upper_digit_set = upper_digit_set + 1;
}



/* What you have to keep in mid is that your final number is something you calculate,
however you cannot display it (you probably could, but it is very complex solution that I should give it a longer thought).
And therefore if we increase lower_digit_set as such: */

lower_digit_set = lower_digit_set + 1;

/* Then the new number will be a combination of both lower_digit_set and upper_digit_set*/

console.log("The actual number is more than once, or twice, or thrice ...etc. of the max_value");
console.log("Number of times we multiply the max value: ", upper_digit_set);
console.log("Then we add our remainder: ", lower_digit_set);

请注意,如果您要计算负数,则应考虑到这一点。此外,解决方案取决于您的需求,这只是一个示例,您可能需要修改它以满足您的需求,但它只是让您大致了解您需要做什么,或者至少是一种思考方式说话。

关于javascript - 如果我需要数 9,007,199,254,740,993 怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25232531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com