1

Im writing an application that automatically adds columns into a div. (Divs inside Div). The issue comes with odd ball column widths such as 6. 6 can't equally divide into 100% so my solution was to find the remainder after the decimal and add it to the last column.

For some reason, when I calculate the remainder it is 0.3999999999999915 instead of .4

Here is my 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);

Should I be using Math.round? Im worried that this may cause some issues later on.


Solved with

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 +'%');
Ray
  • 894
  • 1
  • 6
  • 23

2 Answers2

2

It's not an error. It is just how floating point is designed. You can use number.toFixed() to convert float to string

toFixed accepts a number of digits as a parameter.

Joon
  • 9,346
  • 8
  • 48
  • 75
0

Apply Math.floor function to whole calulation and numCol must be an integer or have to convert into an integer.

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

Instead of

colWid = Math.floor((100 / numCol) * 10) / 10
  • That turns the var into a whole number. The idea was to spread it out equally over each column until it couldn't divide anymore. – Ray Sep 03 '13 at 05:11