LarryBattle / Ratio.js

Rational numbers for Javascript
http://larrybattle.github.com/Ratio.js/
MIT License
113 stars 9 forks source link

Adding ratio to zero ratio results in zero. #48

Closed hakunin closed 11 years ago

hakunin commented 11 years ago

Adding zero ratio to a non-zero ratio results in zero and vice-versa.

Ratio(0, 0).add(1, 2).toString() # "0/0"
Ratio(1, 2).add(0, 0).toString() # "0/0"

fixed locally with adding this to the add function:

if (this.numerator == 0) return obj.clone()
if (obj.numerator == 0) return this.clone()
LarryBattle commented 11 years ago

The results are correct.

Ratio(0, 0) represents 0/0, which is not a number, NaN. Explanation here.

Ratio(0, 0).add(1, 2).toString() // "0/0"
Ratio(1, 2).add(0, 0).toString() // "0/0"

Ratio(0, 0).add(1, 2).toLocaleString() // "NaN"
Ratio(1, 2).add(0, 0).toLocaleString() // "NaN"

Try using Ratio(), which is the same as Ratio(0) or Ratio(0,1), to represent 0 as a fraction.

Ratio().toString() // "0/1"
Ratio().add(1, 2).toString() // "1/2"
Ratio(1, 2).add(0).toString() // "1/2"

You can also use Ratio.prototype.isNaN() to check if the result is a number or not.

// Same as `Ratio.prototype.add()` excepts returns 0 if result is `NaN`
Ratio.prototype.add2 = function(a,b){
    var x = this.add(a,b);
    return (x.isNaN()) ? Ratio() : x;
};

Ratio(0, 0).add2(1, 2).toString(); // 0/1