JavaScript:JavaScript 中两个数字的和是多少?

问题描述

遇到一个问题

有人知道为什么会得到这样的结果吗?

let x = 4153000000000000000 + 99
console.log(x) // 4153000000000000000

let y = 4153000000000000000 + 990
console.log(y) // 4153000000000001000

let z = 4153000000000000000 + 9900
console.log(z) // 4153000000000009700

解决方法

所以您的问题是您使用的数字大于 Integer 的最大容量 9007199254740991。因此任何大于 9007199254740991 的值都会导致异常行为。

使用类似:

let x = BigInt("4153000000000000000")

let y = BigInt("1235")

let z = x + y;

document.write(z);
console.log(z)

,

您的操作结果超出了 JavaScript 数字类型可以安全表示的范围:

# display an input dialog and store the results in the global options hash table
def display_global_options_dialog()

    parameters = [
        # prompt,attr_name,value,enums
        $Wall_Lumber_Size,#[ "Wall Lumber Size","wall.style","38x38|38x64|38x89|38x140|38x184|38x235|38x286|64x64|64x89|64x140|64x184|64x235|64x286|89x89|89x140|89x184|89x235|89x286" ],$wall_styles.join("|") ],[ "Wall Plate Height","wall.height",nil ],[ "Wall Stud Spacing","wall.stud_spacing",[ "Wall Justification  ","window.justify","left|center|right" ],[ "Window Justification  ",[ "Door Justification  ","door.justify",[ "Header Height","header_height",$Header_Size,#[ "Header Size","header_style",$lumber_sections.join("|") ],#[ "Roof Pitch (x/12)  ","pitch",[ "Roof Pitch (deg°)  ",[ "Roof Joist Spacing",'roof.joist_spacing',[ "Floor Joist Spacing",'floor.joist_spacing',]
    prompts = []
    attr_names = []
    values = []
    enums = []
    parameters.each { |a| prompts.push(a[0]); attr_names.push(a[1]); values.push(HouseBuilder::BaseBuilder::GLOBAL_OPTIONS[a[1]]); enums.push(a[2]) }
    results = UI.inputbox(prompts,values,enums,'Global Properties')
    if results
        i = 0
        attr_names.each do |name|
            eval("HouseBuilder::BaseBuilder::GLOBAL_OPTIONS['#{name}'] = results[i]")
            i = i + 1
        end
    end
    return results
end

如果你想处理更大的数字,你可以使用内置的 BigInt 类型:

console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991

,

这是因为 IEEE。大于 2^53 的数字需要用 big Int 来完成。

最安全的最大数是

let a = Number.MAX_SAFE_INTEGER;
//console.log(9007199254740991);

并且最小数量是

 let b = Number.MIN_SAFE_INTEGER;
 //console.log(-9007199254740991);

为了解决这个问题,我们使用BigInt;

let sum = 4153000000000000000n + 99n;
console.log(sum); // 4153000000000000099n

您可以点击 here 了解更多详情。 // MDN

更多参考 here //Stackoverflow

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...