推荐关注
Meteor
JSLint - a JavaScript code quality tool
jsFiddle
D3.js
WebStorm
推荐书目
JavaScript 权威指南第 5 版
Closure: The Definitive Guide
BarZu

一个解决 js 浮点运算精度的代码,比市面上很多解决方案都要准确的方案^_^

  •  
  •   BarZu · Feb 1, 2018 · 6754 views
    This topic created in 3035 days ago, the information mentioned may be changed or developed.
    8 replies    2022-11-05 21:40:37 +08:00
    gomars
        1
    gomars  
       Feb 1, 2018
    整数
    lred
        2
    lred  
       Feb 1, 2018
    之前写过一个库
    https://github.com/fzred/calculatorjs
    楼主的方案不错,比我的简洁很多,介意我直接复制到我的项目吗?
    sundev
        3
    sundev  
       Feb 1, 2018
    再加个方法,修复 toFixed 四舍五入的问题应该就齐活了!
    Mutoo
        4
    Mutoo  
       Feb 1, 2018
    操作数 1:
    0.1000000000000000055511151231257827021181583404541015625
    操作数 2:
    0.200000000000000011102230246251565404236316680908203125
    相加
    结果:0.30000000000000004

    答案为什么不是 0.3000000000000000444089209850062616169452667236328125

    十进制高精度算法还是老老实实逐位运算比较靠谱
    sundev
        5
    sundev  
       Feb 1, 2018
    @Mutoo 他的这个算法只能解决浮点数运算过程中精度丢失的问题,就是把浮点数转换为整数进行运算。但是转换后超过 16 位时,精度一样会丢失,这是 IEEE 754 标准中定义尾数部分只有 53 位决定的。
    AV1
        6
    AV1  
       Feb 1, 2018
    @Mutoo 你的答案也不对吧
    可以用
    https://github.com/MikeMcl/bignumber.js

    BigNumber('0.1000000000000000055511151231257827021181583404541015625')
    .plus('0.200000000000000011102230246251565404236316680908203125')
    .toString();

    答案应该是 0.3000000000000000166533453693773481063544750213623046875
    xieranmaya
        7
    xieranmaya  
       Feb 26, 2018
    Jobing
        8
    Jobing  
       Nov 5, 2022
    可以采用 npm 的一个开源库解决:json-bn 。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   939 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 43ms · UTC 21:00 · PVG 05:00 · LAX 14:00 · JFK 17:00
    ♥ Do have faith in what you're doing.