2

I was just going through the source code of particles.js and came across the following line of code:

this.speed.x = +((-options.maxSpeedX / 2) +
    (Math.random() * options.maxSpeedX)).toFixed(2);

That line of code can be found HERE too.

Now the + sign right at the beginning of the expression has no difference in the equation. E.g.

(-2 + 5) = 3

Now...

+(-2 + 5) = 3 

Another example:

(-5 + 2) = -3

Now..

+(-5 + 2) = -3

Why the plus sign at the beginning of the expression when it makes no difference to the outcome of the equation?

Tushar
  • 78,625
  • 15
  • 134
  • 154
Alexander Solonik
  • 8,718
  • 13
  • 56
  • 133

2 Answers2

2

.toFixed() returns a String. You need to cast it to Number. The unary plus + operator is used to convert/cast the string to number.

Returns

A string representation of numObj that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length. If numObj is greater than 1e+21, this method simply calls Number.prototype.toString() and returns a string in exponential notation.

It is not required in the cases when the result is already a number. Example, +(-2 + 5).

However, in below operation it is required.

this.speed.x = +((-options.maxSpeedX / 2) +
    (Math.random() * options.maxSpeedX)).toFixed(2);
Community
  • 1
  • 1
Tushar
  • 78,625
  • 15
  • 134
  • 154
2

Your code is basically

x = +someNumber.toFixed(2);

Which is

x = +(someNumber.toFixed(2));

because the function call has a higher precedence than the + operator.

This makes

x = +(someNumberFormattedAsARoundedString);

Applying the unary plus operator converts the string back to a number. The net result is the rounding of the initial someNumber.

In this specific case you linked to, this looks like bad practice due to ignorance of what is a IEEE754 floating point number. It looks like the author tried to get fixed precision numbers, thus confusing the number storage and their representation (i.e. formatting).

Denys Séguret
  • 335,116
  • 73
  • 720
  • 697