Archive for the ‘float’ Tag

Javascript floating point fix

Javascript has an annoying bug feature, and it’s the wrong result of simple floating point calculations. Try this:


Surprise! The result is 0.30000000000000004.

This can be quite annoying when programming timers, and doing math of course.

Why is this? It’s because floating points work that way, it’s by design. That’s not really a flaw, it’s just to make the process real fast. Just like your pocket calculator has only 8 digits, which isn’t wrong per se, but it’s never fully mathematically correct. Sun Microsystems has some real hardcore background on the floating point issue.

But for us simple programmers, all we want is a fix, right?

Here is one at Or download the Math Library directly. Kudos to Lars Knickrehm.

floating forms

demo page and complete report

I learned several advanced and quick methods of styling layout without tables, mainly used for forms, where fields should always be aligned:

inline block

label {display:-moz-inline-box; _display: inline-block}

This effectively pushes the fields to a fixed position on the right of the label, and works in almost all browsers

absolute positioning

Absolute positioning of the forms gives you the possibility to shift the fields to the right using relative positioning, as follows

form {position:relative}
input {position:absolute;left:10em}


Last but not least there is floating. This is usually complex because

  1. the height of labels and fields needs to be equal for correct floating/alignment, and
  2. the width of label+height should (almost) equal the form width. There should be room for margin/padding/rounding errors/font-size setting (in case of pixel widths)
  3. form {width: 20em}
    label {float:left; line-height:1.5em; margin-bottom:.2em; width: 9.5em}
    input {float:left; line-height:1.5em; width: 9.5em}

    This can however be fixed by adding a little border or padding to the label, assuming both have the same font size, like this:

    form {width: 20em}
    label {float:left; margin-bottom:1em; width: 10em; padding-right:1px}
    input {float:left}

    In this solution you can play around with margins as much as you like without messing up the display. If anybody can explain to me why this works please let me know.

    update: Ingo Chao explained why it works. The width of the label is exactly half of the form’s width. By adding that 1 pixel, two labels cannot go side by side and thus the next label in row will drop. In the original scenario (no widths, or no extra pixel) the first label moves up, but leaves space on the left, where the next label doesn’t fit, and so it moves down. That doesn’t sound very clear, but I’ll see if I can put an image here soon.

    update2: using label {clear:left} fixes the problems too.