3

Here's something I haven't been able to figure out for the last 30 minutes.

var file = Components.classes["@mozilla.org/file/local;1"].
                      createInstance(Components.interfaces.nsILocalFile);
file.initWithPath( sPath );
...
if ( file.fileSize < (offsetContent+bytesToRead) )
{
    wt.BO.log(file.fileSize + "<" + offsetContent + "+" + bytesToRead);
    bytesToRead = file.fileSize - offsetContent;
}

What the above code displays is: "577 < 50 + 50"... o.O How the hell is 577 < 100? The if statement is true...can't seem to figure why.

Makyen
  • 31,849
  • 12
  • 86
  • 121
AndreiBogdan
  • 10,858
  • 13
  • 58
  • 106

1 Answers1

6

The plus operator (+) is used to concatenate strings, or to add up numbers in JavaScript.

Since offsetContent or bytesToRead are strings, both variables are concatenated:

  • "50" + "50" = "5050"
  • When comparing these values, the string is converted to a number, and
    "5050" == 5050       ->     577 < 5050   is true, of course.

Some methods to fix the code:

// Substract bytesToRead from both sides
if ( file.fileSize - bytesToRead < offsetContent )
// Or, Turn the comparison operator, and make the right side negative
if ( file.fileSize >= -bytesToRead - offsetContent )
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • `parseInt()` and `parseFloat()` would do it to – sdrm Jan 21 '12 at 11:23
  • haha..yes you are right ... can't believe i didn't think about that. I was getting the values from a XML message so...yeah... thanks again. This might go on 9gag. haha – AndreiBogdan Jan 21 '12 at 11:24
  • and even one more method: file.fileSize < (1*offsetContent+1*bytesToRead) :) – AndreiBogdan Jan 21 '12 at 11:26
  • @AndreiBogdan There are several ways to convert numbers. They're **not** equal though, see [this comparison](http://stackoverflow.com/questions/8112757/are-there-are-any-side-effects-of-using-this-method-to-convert-a-string-to-an-in/8112802#8112802). – Rob W Jan 21 '12 at 11:29