V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Can I use?
http://caniuse.com/
Less
http://lesscss.org
Cool Libraries
Bootstrap from Twitter
Jetstrap
liufei123
V2EX  ›  CSS

css flex-grow 设置成小数 为什么计算不准确?

  •  
  •   liufei123 · 2020-06-01 15:17:09 +08:00 · 1931 次点击
    这是一个创建于 1396 天前的主题,其中的信息可能已经有所发展或是发生改变。
    <style>
        *{margin: 0;padding: 0;}
        .box{display:flex;width:600px;height:300px;}
        .left{
            flex-grow: 0.991;
            width: 100px;
            background: green;
        }
    </style>
    
    <div class='box'>
        <div class="left" id="left"></div>
        <script>
            console.log(document.getElementById('left').getBoundingClientRect().width) //595.484375
        </script>
    </div>
    

    在 chrome 打印出来 width 为 595.484375 。 按照 flex 的规范 width 应该为 100+(500*0.991)=595.5 chrome devtools 显示的 width 为 595.48.为什么会出现这种情况啊?

    3 条回复    2020-06-06 11:33:49 +08:00
    noe132
        1
    noe132  
       2020-06-01 15:37:03 +08:00
    猜测:根据 ieee 754 表示,0.991 转换为浮点数时无法精确表示
    产生了误差
    cheese
        2
    cheese  
       2020-06-01 16:10:40 +08:00
    精度问题吧,小数无法用二进制表示,转换的时候丢失了精度
    ericgui
        3
    ericgui  
       2020-06-06 11:33:49 +08:00
    网上的例子,包括官网,可以是小数,但都是 0.x
    比如 0.5,0.6

    0.991 肯定有个精度问题额
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5465 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 08:02 · PVG 16:02 · LAX 01:02 · JFK 04:02
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.