V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
Guidoo
V2EX  ›  JavaScript

请教一个 JS Number 的问题

  •  
  •   Guidoo · 212 天前 · 1515 次点击
    这是一个创建于 212 天前的主题,其中的信息可能已经有所发展或是发生改变。

    Number(44211572582780928)

    为啥会输出 44211572582780930

    13 条回复    2022-11-05 21:41:03 +08:00
    VeryZero
        1
    VeryZero  
       212 天前
    精度丢失
    memedahui
        2
    memedahui  
       212 天前
    js 精度问题,一般的语言都是这种问题了,java 用 bigdecimal 类,js 推荐用 bignumber.js
    hkyshefavor
        3
    hkyshefavor  
       212 天前
    超过 Number.MAX_SAFE_INTEGER 值了,精度丢失
    foolnius
        4
    foolnius  
       212 天前
    可以通过 Number.MAX_SAFE_INTEGER 查看最大值
    Guidoo
        5
    Guidoo  
    OP
       212 天前
    @VeryZero
    @memedahui
    @hkyshefavor 感谢感谢 找到原因了。但是还是好奇为啥会 +2
    yukinotech
        6
    yukinotech  
       212 天前
    安利一下自己写的库,https://github.com/yukinotech/JSBD ,实现 tc39 bigdecimal 提案 https://github.com/tc39/proposal-decimal
    Jooooooooo
        7
    Jooooooooo  
       212 天前
    大数字都建议直接用 string 省事.
    seakingii
        8
    seakingii  
       212 天前
    @Guidoo 别人都说精度丢失了还问为啥 ....
    -
    实在要了解底层原因,建议去看计算机硬件相关的入门书籍
    -
    简单的说,用有限的硬件空间来存储无限的浮点数字难(比如浮点数 1/3 = 0.3333333333333333....),必须要在精度上有个取舍

    -
    如果只是存储之类的,可以用字符串,如果要运算,可以考虑 bignumber.js 这类的外部库
    dudubaba
        9
    dudubaba  
       212 天前
    判断最大安全值 Number.isSafeInteger() 来判断整数的合法性,当超过时可以转换为字符串或者用 BigInt(44211572582780928)
    mxT52CRuqR6o5
        10
    mxT52CRuqR6o5  
       212 天前   ❤️ 1
    IEEE 754
    Guidoo
        11
    Guidoo  
    OP
       212 天前
    Guidoo
        12
    Guidoo  
    OP
       212 天前
    @dudubaba 受教了
    Jobing
        13
    Jobing  
       139 天前
    精度丢失,可以用 npm 库 搜索 json-bn 开源库解决。
    关于   ·   帮助文档   ·   博客   ·   nftychat   ·   API   ·   FAQ   ·   我们的愿景   ·   广告投放   ·   实用小工具   ·   1715 人在线   最高记录 5556   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 46ms · UTC 00:54 · PVG 08:54 · LAX 17:54 · JFK 20:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.