liufei123
V2EX  ›  CSS

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

  •  
  •   liufei123 · Jun 1, 2020 · 2786 views
    This topic created in 2172 days ago, the information mentioned may be changed or developed.
    <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 replies    2020-06-06 11:33:49 +08:00
    noe132
        1
    noe132  
       Jun 1, 2020
    猜测:根据 ieee 754 表示,0.991 转换为浮点数时无法精确表示
    产生了误差
    cheese
        2
    cheese  
       Jun 1, 2020
    精度问题吧,小数无法用二进制表示,转换的时候丢失了精度
    ericgui
        3
    ericgui  
       Jun 6, 2020
    网上的例子,包括官网,可以是小数,但都是 0.x
    比如 0.5,0.6

    0.991 肯定有个精度问题额
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4065 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 56ms · UTC 05:08 · PVG 13:08 · LAX 22:08 · JFK 01:08
    ♥ Do have faith in what you're doing.