计算精确百分比宽度

时间:2013-09-03 04:33:05

标签: javascript jquery html

我正在编写一个自动将列添加到div中的应用程序。 (Div内的Div)。问题是奇数球柱宽度,如6. 6不能平均分为100%所以我的解决方案是找到小数点后的余数并将其添加到最后一列。

出于某种原因,当我计算余数时,它是0.3999999999999915而不是.4

这是我的jQuery

var numCol = $('.column').length,
        colWid = Math.floor((100 / numCol) * 10) / 10,
        numRem = 100 - (colWid * numCol);

    $('.column').width(colWid + '%');
    $('.column:last-child').width(colWid + numRem + "%");

    alert(numRem);

我应该使用Math.round吗?我担心这可能会在以后引起一些问题。


解决了

var numCol = $('.column').length,
        colWid = Math.floor((100 / numCol) * 1000) / 1000,
        numRem = (100 - (colWid * numCol)).toFixed(3);

    $('.column').width(colWid + '%');
    $('.column:last-child').width(Number(numRem)+ colWid +'%');

2 个答案:

答案 0 :(得分:2)

这不是错误。它是如何设计浮点的。 您可以使用number.toFixed()将float转换为字符串

toFixed接受一些数字作为参数。

答案 1 :(得分:0)

将Math.floor函数应用于整个计算,numCol必须是整数或必须转换为整数。

colWid = Math.floor(((100 / numCol) * 10) / 10)

而不是

colWid = Math.floor((100 / numCol) * 10) / 10
相关问题